开发者

Memory Management Objective-C Question

So assume I declared an object and created a retained property for it which is synthesized. So something like that in the header file:

NSArray *array;
@property (retain)....

After it is synthesized, I called release in the dealloc.

Now in the init method, if I want to also dynamically allocate that array, what do I do in terms of releasing it? So: array = [[NSArray alloc] initWithObjects...

How do I keep the object retained as long as the class is r开发者_开发技巧unning without leaking?

Thank you


self.array = [[[NSArray alloc] initWithObjects:...] autorelease];

or

NSArray *newArray = [[NSArray alloc] initWithObjects:...];
self.array = newArray;
[newArray release];

With both options, you additionally have to call [array release]; in dealloc.

By using its setter method, you normally don't have do worry about retains and releases.


All the init* (init, initWith..., etc.) methods return retained objects. The convenience constructors provided by some classes, on the other hand, provide objects that are not retained - or rather, retained, then autoreleased.

More here.

So you are doing the right thing by assigning a retained object to your ivar in the init method, then releasing it in dealloc.

For the rest of the object's life cycle, it would be smart to only use the synthesized accessors, as they take care of retaining and releasing.

All in all, you're good.


In order to take advantage of the goodness of properties, you need to prefix the variable name with self.

array = [[NSArray alloc] initWithObjects:...];

is not the same as

self.array = [[[NSArray alloc] initWithObjects:...] autorelease];

The former will assign the array directly to the instance variable. The latter will invoke the synthesized setArray method, which gives you retain/release for free. This will be useful should you decide to assign a new reference to array at any other point in time in the lifecycle of your class.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜