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?
I know that if I get an object, for example an NSArray, with a
Share
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,
-retainit. Otherwise, do not-retainit. Anytime you retain an ownership interest in an instance, you must-releasethat 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.