开发者

Arrays as properties - retain, etc

开发者 https://www.devze.com 2023-03-13 14:09 出处:网络
I\'m beginning to get my head round all the memory management stuff, but I\'m a bit puzzled by the use of properties with arrays. If I declare the property in the interface like so -

I'm beginning to get my head round all the memory management stuff, but I'm a bit puzzled by the use of properties with arrays. If I declare the property in the interface like so -

@property (nonatomic,retain) NSMutableArray *myArray;

then synthesize it in the implementation, do I need to alloc it when I create the array? Like so -

self.myArray = [[NSMutableArray alloc] init];

or does this result in an extra retain count? Should I just do -

self.myArray = [NSMutableArray array];

and let the setter do the retaining?

Many thanks to anyone who can clarify t开发者_如何学编程his for me!


In both cases you are letting the setter retain your instance.

In this case you are overretaining:

self.myArray = [[NSMutableArray alloc] init];

The setter does and the alloc message sent.

This can be fixed with:

self.myArray = [[[NSMutableArray alloc] init] autorelease];

or

NSMutableArray *newInstance = [[NSMutableArray alloc] init];
self.myArray = newInstance;
[newInstance release];

This is fine

self.myArray = [NSMutableArray array];

however not every class has a convenience class method to return an autoreleased instance.

Have a look at the Memory Management Programming Guide / Object Ownership and Disposal, this will give you a good understanding about when the retain counts increases and when you should release.

0

精彩评论

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