开发者

Local variable assign versus direct assign; properties and memory

In objective-c I see a lot of sample code where the author assigns a local variable, assig开发者_高级运维ns 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.


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.


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];


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜