I’m an objective-c newbie and I just can’t understand why it is a bad idea to release object that doesn’t belong to me.
Let’s say I have this in the method called Europe
//initForStringTheory is a class init method;
Collider *LHC = [Collider initForStringTheory];
//Colliders is a NSMutableArray
[Colliders addObject: LHC]
[LHC release]
I’m adviced not to release LHC in Europe as Europe does not own LHC, it only has a pointer to it. And therefore I should make good use of the autorelease pool and do
//newCollider is a pointer for the newly created instance in initForStringTheory
return [newCollider autorelease];
in initForStringTheory. But why?
Doesn’t the pointer in Europe points to the instance too? Why can’t I just release LHC in Europe instead of returning a autoreleasing newCollider in the init method?
It’s all a question of what
initForStringTheoryreturns – if this is a convenience initialization method such as[NSArray arrayWithObjects...]or[NSString stringWithFormat...], it creates an autoreleased instance that you do not need to release after adding it to your collection. However, if this is an initialization that returns an initialized non-autoreleased instance, it is your responsibility to release the local instance definition in your method right after adding it to the collection.The retain count of the object is incremented by 1 when it is added, so you don’t want it to be 2 because you haven’t released/autoreleased it after instantiation (would result in a memory leak because the object will never become deallocated, even when it’s out of the array).
Read this:
http://developer.apple.com/library/mac/#documentation/CoreFoundation/Conceptual/CFMemoryMgmt/Concepts/Ownership.html