I am sorta new on Objective-C and I am trying to understand some stuff about this retain release mechanism.
Suppose I need an array to last the entire life of the application. So, suppose I create the array using something like
myArray = [[NSMutableArray alloc] init];
at the beginning of the app.
During the app, this array may have all objects removed, added objects from other arrays, etc. Suppose also, that during one of these operations of adding objects, I add autoreleased objects to the array. Two questions:
-
will the objects added to that array always be live and never deallocated while the array is allocated?
-
I know that adding an object to an array will increase its retain count. Is this also valid for autoreleased objects? (perhaps autoreleased arrays coming from other methods)
thanks
will the objects added to that array always be live and never deallocated while the array is allocated?
They will under normal circumstances, i.e., provided you’re not overreleasing them. For instance,
Considering that no other code has claimed ownership of
someObject, it won’t be ‘live’ because it was overreleased.I know that adding an object to an array will increase its retain count. Is this also valid for autoreleased objects? (perhaps autoreleased arrays coming from other methods)
Yes. Collections won’t look at retain counts or autorelease status whilst adding objects, nor they should. An array simply sends
-retainto the object being added and hence takes ownership of that object, regardless of other code owning (or not owning) the object.The whole point of memory management and object ownership is to consider ownership in a relative way: if a collection needs an object, it’ll take ownership of the object; if the collection is released or the object is removed from the collection, it’ll relinquish ownership of the object. The collection doesn’t care about the object being owned by other objects or code — it is only concerned about its own perspective of owning the object. The same principle should apply to your code.