Reputation: 1695
I'm creating an NSDictionary which maps objects to integers, and because NSDictionaries don't handle anything but objects I have to wrap each integer in an NSNumber object with [NSNumber numberWithInt:30] or what have you. What I'm not clear about is whether or not I need to release all of those NSNumber objects I'm creating. I'm not actually alloc'ing the space for them, so they must be in the autorelease pool, but can I be sure that the NSDictionary object is retaining and releasing them properly? Let's say I'm setting
NSDictionary * myDict = [[NSDictionary alloc] initWithObjectsAndKeys: objectOne, [NSNumber numberWithInt: 30], nil];
and I'm properly releasing the NSDictionary when I'm done with it (since I am alloc'ing the space for that within my own code).
Upvotes: 2
Views: 717
Reputation: 150635
No. You're doing fine.
You are adding an autoreleased NSNumber to a dictionary. The dictionary will retain the NSNumber, so when it eventually autoreleases, it will still be valid.
However just a couple of points so you don't get careless. You realise that the NSNumber is the key and objectOne is the value that is being stored in the dictionary? This is okay, because NSNumber conforms to the NSCopying protocol, which is a requirement for objects that are used as keys.
Upvotes: 1
Reputation: 1267
nope the NSNumber objects are autoreleased.
Adding them to an NSDictionary will cause a retain message to be send to each NSNumber object you add.
According to the Memory Management Rules you don't own these objects - NSDictionary does that somehow - and thus you are not responsible releasing them, the NSDictionary object will do that.
But you own the NSDictionary created with alloc & initWithObjectsAndKeys:. Therefore you need to take care about managing memory of the myDict object.
Upvotes: 2