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.
精彩评论