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.
The rules are generally pretty simple. If you get an object in one of the following ways:
then you need to release it at some point — in the same method, or your
deallocmethod, generally. In other words, balance your calls toalloc,retain,copy, andmutableCopywith a matchingreleasecall.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.
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.)