开发者

Which way is the correct way to allocate memory with a property?

开发者 https://www.devze.com 2023-04-04 15:09 出处:网络
Which way is correct? NSString *c = [开发者_开发百科[NSString alloc] init]; self.character = c; [c release];

Which way is correct?

NSString *c = [开发者_开发百科[NSString alloc] init];
self.character = c;
[c release];

or

self.character = [[NSString alloc] init];

And why? Thanks.


It depends on how your property is declared. If you used

@property (nonatomic, retain) NSString *someString;

The setter will be created to retain someString, in which case the correct way is your first method. If you used:

@property (nonatomic, assign) NSString *someString;

Your second method will be correct, since it will just assign the pointer and not retain anything.


It depends on how you've defined your property.

If it's copy or retain, the synthesized setter (setCharacter: in your example) will take ownership of any objects you assign to the property. In this situation your first example is correct. The second would lead to a memory leak as you've claimed ownership of the NSString twice and you will (probably) only relinquish ownership once; thus the memory can never be reclaimed.

If it's assign on the other hand, the setter won't do anything special and your second example would be correct. The first would result in an EXC_BAD_ACCESS error if you tried to do anything with the NSString. I should note that you generally only use assign for primitive types and delegates.

I suggest you have a read over the Memory Management Programming Guide and the Declared Properties section of The Objective-C Programming Language guide.


The answer depends on your @property definition. Likely it's something like (retain) or (copy) for an NSString. In that case, assigning to self.character will increment the retain count. So the bottom:

self.character = [[NSString alloc] init];

You've set the retain count to 1 with the alloc and self.character will also retain it for a count of 2, so that'll leak. Should be

self.character = [[[NSString alloc] init] autorelease];

or the top version.


The answer to this now with iOS 5 is to use ARC.

0

精彩评论

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