开发者

Objective C property retain count

开发者 https://www.devze.com 2023-01-16 00:26 出处:网络
if I have a property such as @property (nonatomic, retain) NSArray *myArray; and then I set it as follows

if I have a property such as

@property (nonatomic, retain) NSArray *myArray;

and then I set it as follows

开发者_StackOverflow社区[self setMyArray:[[NSArray alloc]init]];

do I have a retain count of 2?

When I release it in my dealloc method will there still be a retain count of 1?


You do in fact have one too many references if you set the property with just the return of [[NSArray alloc] init].

You can use [self setMyArray:[NSArray array]] to avoid that as the 'array' method returns an auto-released object.

Or...

NSArray* newArray = [[NSArray alloc] init];
[self setMyArray:newArray];
[newArray release];

... if you'd prefer not to use an auto-released object.


Yep you will have a retain count of 2. another option to avoid that would be to say:

[self setMyArray:[NSArray array]];

that way it is autoreleased and will be taken care of in the dealloc if you release it once.

A nice thing about having @property(retain) is that if you set it to something else it will release the old value.

0

精彩评论

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