Re: NSMutableDictionary, NSNumber and more memory management
Re: NSMutableDictionary, NSNumber and more memory management
- Subject: Re: NSMutableDictionary, NSNumber and more memory management
- From: Joshua Pennington <email@hidden>
- Date: Thu, 28 Aug 2008 07:33:25 -0500
The safest thing to do is to check the documentation for a method and
see what it says about object ownership. A good rule of thumb is,
however, when a convenience method returns an object, you do not have
ownership over it. If you need it to persist, you should retain it (at
which point you now have ownership and should release it whenever you
are finished).
When in doubt, check the memory management guide:
<http://developer.apple.com/documentation/Cocoa/Conceptual/MemoryMgmt/MemoryMgmt.html
>
Cheers,
Joshua
On Aug 28, 2008, at 7:28 AM, Memo Akten wrote:
Thanks Joshua, that clears up the memory stuff... i think i finally
get it now: unless you explicitly alloc or retain, you never need to
release...
On 28 Aug 2008, at 13:12, Joshua Pennington wrote:
On Aug 28, 2008, at 6:46 AM, Memo Akten <email@hidden> wrote:
q1:
Is this all correct? When you setObject, the docs say that the
object receives a retain, so that means its safe (and correct) for
me to do the above? Do I need to release the NSNumbers in dealloc?
or does the NSMutableDictionary release them? I think its the
latter but just wanted to double check.
numberWithUnsignedInteger: returns an object which you do not have
ownership over and as a result, you are not responsible for
releasing it. NSDictionary will retain it when setValue:forKey: is
messaged.
q2:
this is my updating code:
- (void) updateValue:(NSString*)key {
id oldValue = [myDict objectForKey:key];
id newValue = [NSNumber numberWithUnsignedInteger:([oldValue
unsignedIntegerValue] + 1)];
[myDict setObject:newValue forKey:key];
[oldValue release]; // do I need to release this?
objectForKey: returns an object over which you do not have
ownership and as a result you do not have to release it after. When
you call setValue:forKey: it retains newValue and releases it's
reference to the original key.
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden