views:

30

answers:

3

I know that if I get an object, for example an NSArray, with a method like [NSArray array], it will be autoreleased. So I don't have to do a release myself. My question is, do I have to retain it after I get it this way? I wouldn't have thought so, since the count starts at 1 and it won't be released until the pool is released, but I've gotten a few bad access errors from these objects when I don't. So to fix them, I'm retaining these objects, and then releasing them myself later. What's going on in this case? Am I still not grasping objective-c memory management?

A: 

An autoreleased object will have its retain count decremented at the end of the run loop. So if you have an object that you want to keep around longer than the end of the run loop, yes, you have to retain it.

Carl Norum
+3  A: 

I heartily advise you to stop thinking about retain counts. Instead, think about ownership: do you want to claim a piece of ownership of an instance (i.e. do you want to make sure it stays around until you say otherwise)? If so, -retain it. Otherwise, do not -retain it. Anytime you retain an ownership interest in an instance, you must -release that interest some time in the future or the instance will never be deallocated.

You can assume that any method that doesn't match the alloc/new/copy pattern returns instances in which you do not have an ownership interest. If you want them to stick around beyond the current stack frame, retain them.

For this and all other Objective-C memory questions, read the Memory Management Programming Guide. Then re-read it. Again. It is the authoritative reference on the subject. It will be your friend.

Barry Wark
A: 

You don't retain unless you need to claim ownership of the object. You need to post some code or describe what you're doing before anyone can help you determine how and why you're getting errors.

Preston