views:

41

answers:

2

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 objects 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.

+2  A: 

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.)

mipadi
ah, it's the alloc effectively retains (in terms of release) that I was thinking of in terms of the auto-retain...
Brian Postow
+2  A: 

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

Barry Wark