MightyMeta
MightyMeta

Reputation: 609

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

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!

Upvotes: 1

Views: 89

Answers (2)

Chris Trahey
Chris Trahey

Reputation: 18290

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!!

Upvotes: 1

Stunner
Stunner

Reputation: 12194

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.

Upvotes: 1

Related Questions