Is it necessary to use a temporary variable when setting a properties' value? - objective-c

I have a (retained) UIImage property that is being used to hold a user selected image.
This is the code I have at present when the user makes a selection:
- (IBAction) selectImage1 {
UIImage *image = [UIImage imageNamed: #"image1-big.png"];
self.bigImage = image;
}
but I'm wondering if it is possible to omit the use of the temporary variable convenience method and just do this:
- (IBAction) selectImage1 {
self.bigImage = [UIImage imageNamed: #"image1-big.png"];
}
If there are problems with this second method (I'm guessing something to do with memory management), could someone please explain?
Thank you!

The second way is perfectly fine. The line UIImage *image = [UIImage imageNamed: #"image1-big.png"]; gives you a variable image that is auto-released. Assigning it to your ivar via the self.bigImage = image calls bigImage's setter method which retains the value. Thus the line self.bigImage = [UIImage imageNamed: #"image1-big.png"]; is equivalent to the more verbose way.

There is no difference in terms of memory management between the two snippets you posted; unless you get really specific about retain counts in between the two lines in the first snippet.
In an ARC environment, the local variable will be a 'strong' pointer, however it is released when the method leaves scope. In the second snippet, there is no intermediate retain/release'd pointer, and so may actually be slightly more efficient.
The places I have seen the first snippet's technique be necessary are when you have a weak pointer (i.e. a weak #property) where setting self.foo = [UIView ... would immediately allow it to be released. In these cases it is better to use a local variable to keep it around while you work with it:
UIView *someFoo = [UIView...
[self addSubview:someFoo];
self.someWeakProperty = someFoo;
compare with:
self.someWeakProperty = [UIView...
[self addSubview:self.someWeakProperty]; // it's already nil!!

Related

Checking whether two objects being used in two arrays are the same

I have two arrays that include 5 pictures of a background with a solid color. This is the code used to put the images into the arrays:
self.colorArray = #[
[UIImage imageNamed:#"orange_square"],
[UIImage imageNamed:#"purple_square"],
[UIImage imageNamed:#"red_square"],
[UIImage imageNamed:#"blue_square"],
[UIImage imageNamed:#"green_square"],
];
self.iconColorArray = #[
[UIImage imageNamed:#"orange_icon"],
[UIImage imageNamed:#"purple_icon"],
[UIImage imageNamed:#"red_icon"],
[UIImage imageNamed:#"blue_icon"],
[UIImage imageNamed:#"green_icon"],
];
As you can see the images are respectively put in order in terms of the color of their background. (I use different images for the arrays because iconColorArray is being used for a smaller UIImageView)
The app randomly changes the images of the two UIImageViews.
What I want is a if-else statement to compare the two arrays to see if the same objectAtIndex is being used. Exp: If orange_square is used for one UIImageView and orange_icon is being used for the other, the condition in the if-else statement will return true.
Basically to answer my question, just tell me how I would get the index of an object being used by a UIImageView in a array.
Edit:
Using Matt's advice, I changed the code to:
NSUInteger d = [self.colorArray indexOfObject:self.squareOne.image];
NSUInteger e = [self.iconColorArray indexOfObject:self.icon.image];
Now, I can compare them.
The way you get the index of an object is with (wait for it) indexOfObject:.
The problem is that the use of this method presupposes that this object can be compared for equality. I don't know whether UIImage does; I rather doubt it, but you can try.
Another possibility is indexOfObjectIdenticalTo:; this might work if the image is not copied by the image view but is an actual reference to one and the same image as the image in the array.
Having said all that, which would I do? None of them. I wouldn't even keep arrays of images; it's terribly wasteful of memory, and your app is likely to crash before it gets off the ground. What I would do is keep an array of the names of the images; strings are tiny, images are huge. And in order to make the comparison, I would subclass UIImageView to have a name property so that I could assign the name as well as the image, and now the problem is trivial.
Or you could even display the images through a view controller of their own, and give the view controller the name property. As a matter of fact I happen to have an example of doing that:
https://github.com/mattneub/Programming-iOS-Book-Examples/blob/master/bk2ch06p311pageController/ch19p626pageController/Pep.swift
And in fact if you explore the rest of that project you will see that I the proceed to do exactly what you are asking to do: to learn what pep boy is being displayed, I ask the Pep object for its boy string and I look up its index in a list of Pep boys:
https://github.com/mattneub/Programming-iOS-Book-Examples/blob/master/bk2ch06p311pageController/ch19p626pageController/AppDelegate.swift
It's in Swift so I use find instead of indexOfObject: but it amounts to the same thing.
You could create a third object as a dictionary, where the image square names names are the keys are the keys. And then you colorArray and iconColorArray could derive from this dictionary.
self.imageMap = { #"orange_square" : #"orange_icon",
#"purple_square" : #"purple_icon" }
- (BOOL)squareUsed:(UIImage *)square isSameAsIcon:(UIImage *)iconUsed {
for (NSString *key in self.imageMap) {
if ([[UIImage imageNamed:key] isEqual:square]) {
if ([UIImage imageNamed:self.imageMap[key]] isEqual:iconUsed]) {
return YES;
}
// We matched the square and the icon didn't match.
return NO;
}
}
// We never matched the square. Assert?
return NO;
}

Objective-c convert a parent class to its derived class

I have a custom class named MyImage inherit from UIImage. Now I have a UIImage object, is there any ways to convert it into a MyImage object?
Update
Sorry for being unclear.
I cannot use a category because I need to add new properties to my class.
What I want to accomplish is to just let my MyImage object point to the original UIImage object.
Update 2
I tried something like this:
- (MyImage*)initWithUIImage:(UIImage *)image {
if (self = [super init]) {
self = image;
}
return self;
}
Obvious it does not work.
Also, since UIImage does not have a method named 'initWithImage:(UIImage*)', I cannot write something like
myImage = [[MyImage alloc] initWithImage:uiImage];
I also tried
self = [image copy]
But the return value is still a UIImage object, not a MyImage object.
Update 3
In MyImage, I need to add 3 properties: url, width, and height. Since I am writing a instant messaging app, and when receiving a new image message, I only have its url, width, and height. Then I assign those to a MyImage object, and download the image in the background.
Now given an original UIImage A, I want to create a new MyImage object B, which points to the same image as A, but with those new properties unassigned. Then I manually assign url, width, and height to B.
to #rmaddy, could you tell me how to write the method
[[MyImage alloc] initWithImage:(UIImage*)]
?
One way I can come up is first convert the UIImage object to NSData, then use
[MyImage imageWithData:]
Is there a better way?
I do not necessarily recommend this as a solution, but there is indeed a way to do exactly what you are looking for. It is called ISA Swizzling. Think of it like method swizzling but for Classes instead of methods.
Take a look at the Objective-C runtime's object_setClass [link]
I won't go into it (there are better resources out there), but this is essentially how KVO works. Regardless, it would be helpful if you better described the functionality of your UIImage subclass, so that we could help describe why a custom initializer as rmaddy describes is probably the best solution.
Your MyImage class is a subclass of UIImage, so if you're creating a new instance you need to properly initialize the superclass as well. UIImage doesn't provide a method to do that from another UIImage instance, but you can use a CGImage, and you can get one of those from the existing image. So do this:
- (MyImage*)initWithUIImage:(UIImage *)image {
if (self = [super initWithCGImage:image.CGImage]) {
// put any necessary MyImage-specific stuff here
}
return self;
}

How to override a method in framework's class (runtime)

problem:
framework will cache the image data when above:
[UIImage imageNamed:]
I don't want the caching happen,so I can replace it by
[UIImage imageOfContentOfFile:]
Seems solved,but after my tests,in xib's instantiate progress, framework uses imageNamed: rather than imageOfContentOfFile.
That is, images loaded by xib still cached.
So I try to override the UIImage's imageNamed: method, make all this method DO NOT CACHE.
--try1. category:
#implementation UIImage (ImageNamedNoCache)
+ (UIImage *)imageNamed:(NSString *)name;
{
NSString* path = [[NSBundle mainBundle] pathForResource:name ofType:nil];
return [UIImage imageWithContentsOfFile:path];
}
#end
--result:warning."Category is implementing a method which will also be implemented by its primary class"
--try2. runtime replace the method's imp
//get super method
Method method_imageNamed = class_getClassMethod([UIImage class], #selector(imageNamed:));
//get my method
Method method_myImageNamed = class_getClassMethod([self class], #selector(myImageNamed:));
//get my imp
IMP imp_myImageNamed = method_getImplementation(method_myImageNamed);
//set super method's imp to my imp
method_setImplementation(method_imageNamed, imp_myImageNamed);
--result
these too try only work when I invoke [UIImage imageNamed:]
but xib's instantiation doesn't work.
help me, thanks
Sounds like a job for method swizzling. I find it dangerous and unnecessary, but if you are so inclined, it is an option. Use at your own risk.
The category method should be fine, just give your method a different name. It's my understanding that it's not good practice to override methods in a category, but adding a new one is fine.
Correct me if I do not interpret correctly, but it looks like your core problem is that you are trying to get framework (i.e., Apple code) to call imageWithContentsOfFile instead of imageNamed when loading xibs.
A third option might be to leave the UIImageViews in the xib 'blank' as a placeholder, and then programmatically loading UIImages into them later (for example in the FileOwner's init code), perhaps with the help of the 'tag' property + a dictionary to determine the right image, if it's convenient. Or you could even create both the images and their views dynamically instead of keeping them in the xib file. Obviously there are lots of tradeoffs here.
Your solution isn't good :) Caching is used for good reasons.
Just don't use [UIImage imageNamed:] In YOUR code, and all will be fine
If you Actually need not to cache your images, you should use method #2.
NOTE: Images(actually, all objects) from XIBS are being loaded with -[object initWithCoder:], and not with [UIImage imageNamed:] or [UIImage imageWithContentsOfFile:]

Objects not initialized

in objective C, I can do the following
UIImage *myImage = [UIImage imageNamed:#"myPhoto.jpg"];
variable.image = myImage;
and this works just fine. but the object named "myImage" was never initialized, and the UIImage never had any memory allocated and yet the code still works..
Can someone explain what's going on here?
Yes, the object was initialised. The imageNamed: method allocates and initialises an object, sends it an autorelease message, then returns the memory address to you. You store that memory address in the pointer called myImage.
myImage and the object are two different things. myImage merely points at a memory location. It is not the object itself.
You can pass around objects without assigning them to variables, and you can assign one object to many variables.
Consider this:
UIImage *imageOne;
UIImage *imageTwo;
imageOne = [UIImage imageNamed:#"myPhoto.jpg"];
imageTwo = imageOne;
The image wasn't copied. There is only one object in existence. Both variables point to it.
Now consider this:
NSLog(#"%#", [UIImage imageNamed:#"myPhoto.jpg"]);
You didn't assign it to any variable. But the object still existed, right?
Have a look in the documentation for UIImage. Under the heading "Cached Image Loading Routines" and "Creating New Images" are some methods with a + where you might expect a -. This means that calling these methods is the same as calling [[[UIImage alloc] init] autorelease];, though some of them do more (as in custom initialization).
Lots of other Objective C objects have similar methods, for example, NSArray has a method +(id)array that creates and returns an empty array. Your main indicator here is the + instead of the -, but I always check the documentation to check how the initialization is handled and to make sure the object is autoreleased.

Is it safe to call initializers multiple times on the same 'alloc'ed object?

I can construct a UIImageView object with myImageView = [[UIImageView alloc] initWithImage:image];
Following application activity affecting the display, if I want to change the image on the UIImageView. I can do so by reassigning it with myImageView.image = someNewImage. However this doesn't seem to update the frame dimensions. I can modify those manually, but I have observed in practice that calling [myImageView initWithImage:someNewImage] does that for me, and has the advantage of being terser.
However I not sure if it is officially a breach of protocol in Objective C to make multiple calls to init methods on an object constructed by a single alloc. I wouldn't use it unless it was safe (guaranteed not to crash or cause leaks). Is there evidence that it is unsafe?
My research so far...
This article gives general detail about 'alloc' and 'init' on objects
http://developer.apple.com/library/mac/documentation/cocoa/Conceptual/ObjectiveC/Articles/ocAllocInit.html
This is related SO question
Why are alloc and init called separately in Objective-C?
This blog article warns suppliers of objects that their init methods may be called multiple times as an effect of the initialization process.
http://www.friday.com/bbum/2009/09/06/iniailize-can-be-executed-multiple-times-load-not-so-much/
No.
-init is written assuming that it is only called once. For example, -initWithImage quoted in Apple's documentation you quoted is implemented as
- (id)initWithImage:(NSImage *)anImage {
...
if (self) {
image = [anImage retain];
}
return self;
}
This assumes that the ivar image doesn't point to a retained object. If called twice, it leaks image.
Call -init... only once per alloc, and call -init... immediately after alloc by combining them as usual:
SomeClass* foo=[[SomeClass alloc] init...: ... ];
You should never separate them, because [anAllocedObject init...] might return something different from anAllocedObject.
No, init (or one of it's variants) should only be called once on any object, as Yuji explained. As far as your UIImageView issue goes, I believe you can just call [imageView sizeToFit] after assigning your new image, and it will automatically resize it for you.