views:

53

answers:

3

In objective-c I see a lot of sample code where the author assigns a local variable, assigns it to a property, then releases the local variable. Is there a practical reason for doing this? I've been just assigning directly to the property for the most part. Would that cause a memory leak in any way? I guess I'd like to know if there's any difference between this:

HomeScreenBtns *localHomeScreenBtns = [[HomeScreenBtns alloc] init];
self.homeScreenBtns = localHomeScreenBtns;
[localHomeScreenBtns release];

and this:

self.homeScreenBtns = [[HomeScreenBtns alloc] init];

Assuming that homeScreenBtns is a property like so:

@property (nonatomic, retain) HomeScreenBtns *homeScreenBtns;

I'm getting ready to submit my application to the app store so I'm in full optimize/QA mode.

+4  A: 

Assuming:

@property (nonatomic,retain) HomeScreenBtns *homeScreenBtns;
  1. HomeScreenBtns *localHomeScreenBtns = [[HomeScreenBtns alloc] init];
  2. self.homeScreenBtns = localHomeScreenBtns;
  3. [localHomeScreenBtns release];

Then (1) implies a retain. (2) implies a second retain because the property says so. (3) releases the retain in the local scope created by (1).

If you don't do (3), you'll leak eventually.

This is all documented in the memory management guide.

bbum
Right, I get the 1,2,3. Is there any reason I can't directly assign the property though?
Typeoneerror
+2  A: 

You can't do this:

self.homeScreenBtns = [[HomeScreenBtns alloc] init];

because when you [[HomeScreenBtns alloc] init] you create an object with alloc so that object has a retain count of 1. Then when you set that object to homeScreenBtns it has a retain count of 2 because homeScreenBtns also retains that object. Thus the retain count of the object can never get back to 0 because the only release statement is in the setter method of homeScreenBtns. Thus you leak memory. If you want to do it in one statement instead of the first way you listed you could use:

self.homeScreenBtns = [[[HomeScreenBtns alloc] init] autorelease];
regulus6633
Crap, looks like I've got some rewriting to do! Thanks. Surprised my app hasn't crashed at all really.
Typeoneerror
+1  A: 

As the memory management guides say - if you create an instance of something, you must manage and release it.

 ...allocate]init];

Creates an instance. Regardless of what you do with it in your code, you must have a matching ' ... release]' or you will cause a memory leak.

If as you say you have been writing code which allocs an instance of an class and sets a property on the same line, you WILL HAVE A MEMORY LEAK ... And your program will crash ... After first ... Slowing ... Down ................ Whilst ..... Using ........up ............memo.............

Derek Clarkson