Re: NSMutableDictionary not sending release message to contained objects at dealloc time
Re: NSMutableDictionary not sending release message to contained objects at dealloc time
- Subject: Re: NSMutableDictionary not sending release message to contained objects at dealloc time
- From: Jonathan Jackel <email@hidden>
- Date: Sat, 12 Apr 2003 09:41:19 -0400
For reference, the original code:
MYObject *obj = [[MYObject alloc] init];
NSMutableDictionary *dict = [NSMutableDictionary
dictionaryWithObjectsAndKeys:obj, @"Key", nil];
NSMutableArray *arr = [[NSMutableArray arrayWithObjects:dict, nil];
NSLog(@"Retain count on obj is %d", [obj retainCount]); // count is 2
(correct)
// remove the dictionary, which should send release to obj as well
[arr removeObjectAtIndex:0];
NSLog(@"Retain count on obj is %d", [obj retainCount]); // count is
still 2 (INCORRECT!)
Greg wrote:
It shouldn't. The contents of the dictionary should be sent a release
message when the dictionary itself is releaed, to balance the retain
message they are sent when added to the dictionary.
But that's not what your code does. The dictionary is not released
until LATER! You are, as I suspected, misunderstanding what
autorelease does.
This is how I think it works (should work):
- allocate object (retain count 1, regardless of whether autoreleased)
- add object to collection (retain count 2)
- remove object from collection (retain count 1)
- deallocate object when retain count hits 0 again (either via
autorelease or explicit release, depending on method with which object
was obtained)
You've got that right. You are misunderstanding WHEN autorelease does
its job, which is not until (at least) execution leaves the scope where
dict was declared. The Application Kit creates a an autorelease pool
at the beginning of the event loop. Objects (like dict) are added to
this pool, and the pool is released at the end of the event loop. The
execution of the code you posted all happens within the same event
loop, so the same pool sticks around and, as a result, dict sticks
around.
This is exactly what you probably would want in a real program. Your
code may need to do something with dict after it is removed from the
array, e.g., pass it as an argument to another method. Your code can
do so as long as it does so within the scope where dict was declared.
Jonathan
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.