views:

56

answers:

1

[I have read the Cocoa memory management rules, but still want to be certain, and would like to know if this is good form.]

My class has a mutable dictionary ivar:

NSMutableDictionary *m_Dict;

...

m_Dict = [NSMutableDictionary dictionaryWithCapacity:10];
[m_Dict retain];

At some point I'll add a mutable array to the dictionary:

NSMutableArray *array = [NSMutableArray arrayWithCapacity:100];
[m_Dict setObject:array forKey: @"myArray"];

At this point, I believe that the array object has been retained by the dictionary. Therefore I am not retaining the object prior to adding it to the dictionary. Is this correct?

Later, I will access the array, for read purposes:

NSMutableArray *array = [m_Dict objectForKey: @"myArray"];

Q1. What is being returned by objectForKey? Is it a pointer to the object being held in the dictionary? Or a pointer to a COPY of the object? (I am presuming simply a pointer to the existing object is being returned.)

Q2. What has happened here, memory management wise? I am presuming that 'array' points to an object that is still retained (by the owning dictionary object) and that I do not have to retain the object to work with it. Correct?

Thanks.

+3  A: 

Q1) The same pointer to the Objective-C array that you added before is returned. No copy is made.

Q2) Correct. All items in the array are owned by the array. If something owns something else it keeps a retain count on it.

When you remove the object from the array the retain count is reduced and the object is (maybe) deallocated.

Lothar
Thanks, that's much clearer now.
SirRatty