开发者

Reference on when to release in Objective-C

开发者 https://www.devze.com 2023-01-09 06:02 出处:网络
I\'m having a recurring problem in Objective-C. I\'m either releasing things too many time, or not enough. or perhaps I\'m not retaining them enough...

I'm having a recurring problem in Objective-C. I'm either releasing things too many time, or not enough. or perhaps I'm not retaining them enough...

Can someone point me at a good reference that will give me a rule of thumb on when I need to retain and release?

For example:

I remember reading somewhere that some objects come pre-retained, so I need to release them, but not retain them. Which obj开发者_开发百科ects are these?

if I alloc an object and only need it in that method, do I need to release it? retain it?

Obviously, if I retained something, I needtorelease it, but beyond that, I get a bit lost.


The rules are generally pretty simple. If you get an object in one of the following ways:

id obj = [[MyObject alloc] init];
id obj = [myObject retain];
id obj = [myObject copy];
id obj = [myObject mutableCopy];

then you need to release it at some point -- in the same method, or your dealloc method, generally. In other words, balance your calls to alloc, retain, copy, and mutableCopy with a matching release call.

I remember reading somewhere that some objects come pre-retained, so I need to release them, but not retain them. Which objects are these?

This happens rarely. The documentation for the called method should specify that you are responsible for releasing the returned object; otherwise, you should assume you're receiving an autoreleased object.

if I alloc an object and only need it in that method, do I need to release it? retain it?

Yes, you need to release it (but you don't need to retain it). (You can also use one of the convenience methods that return an autoreleased object if you're only going to use it in that method.)


There is one and only one canonical reference: Apple's Memory Management Guide for Cocoa or iPhone.

0

精彩评论

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