I have a mutable array that has been retained.
This array contain dictionaries with lots of keys. Each dictionary contains objects.
Do I have to retain the dictionaries before adding them to the mutable array or will the array itself retain everything that is added to it (because it is already retained), including the sub objects of its objects in the hierarchy?
thanks.
A Foundation container, like
NSArrayorNSDictionary, retains the objects it directly owns, but not subobjects owned by the objects.For example, if
NSArray*acontainsNSArray*band it in turn containsNSArray*c,aretainsbandbretainscbutadoesn’t retainc.That said, your are thinking from a wrong perspective. It’s not correct for you to wonder such as “do I have to retain this object (say
x) before passingxto another objecty, becauseymight not retain it appropriately?” The point ofretain/releaseis that to make sure an object retains and releases objects it owns. You trust other objects to do the same.Then, all you have to make sure if you put an object
xto an arrayy, is for you not to releasex(if it’s not autoreleased) once it becomes unnecessary to you. Ifyneeds it,yretains it, so you don’t have to care about it.Say you have a pre-existing
NSMutableArray*array. Then you would do in a method something like this:You see, it’s the array’s responsibility to retain the dictionary, if that array needs it. It needs it, and so it retains it. You don’t have to care about that.
The method’s responsibility is to retain the dictionary if the method needs it, to release it if the method no longer needs it. So, as shown above, the method releases it once it’s done with it by adding it to the array.
Again: the whole point of
retain/releaseis to allow you to consider the life cycle of an object very locally in the code.Whenever you call a method
method:of another objectaby passing an objectb, you don’t have to worry as you do now whethermethod:retainsbor not, and you don’t have to worry if you need to retainbbefore passingbtomethod:.It is because every method in the Cocoa framework, and every method you write, retain the object
bpassed to it if the method needs it later, and don’t retainbif it doesn’t need it later.