Reputation: 5372
I'm learning obj-c and I have a question about memory management:
Say I have a function that returns an NSDictionary, "fDictionary",
NSDictionary *fDictionary {
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:1], @"blah",nil];
return dict
}
that is called by a particular method:
-(int)fNumber {
NSDictionary *f = fDictionary();
return [[f objectForKey:@"blah"] intValue];
}
What I'm unclear about is how/where I should be releasing the NSDictionary object.
Should I release it in the method, or autorelease it in the function?
Upvotes: 0
Views: 85
Reputation: 2925
No.
NSDictionary dictionaryWithObjectsAndKeys:
(which is really just [[[NSDictonary alloc]initWithObjectsAndKeys:, nil]autorelease]
) returns an autoreleased NSDictionary
. This means the dictionary will automatically be released when the computer decides it is no longer needed.
If in fDictionary()
the dictionary was alloc
ed, you would need to release it manually. It is a rule of thumb to always return autoreleased objects from functions/methods, so the user of the functions/methods does not have to worry about memory management.
Upvotes: 0
Reputation: 24429
If you have received an object from a method which name begins with “alloc”, “new”, “copy”, or “mutableCopy”, you have to release or auto-release it. Otherwise it is already autoreleased.
If you have retained something, you have to release it, nothing else will do that for you.
Every Obj-C programmer must read Memory Management Guide.
Upvotes: 0
Reputation: 9124
The general rule is if your code alloc's something, you need to release or auto-release it.
If this was someone else's function, you would expect that the returned dictionary was autoreleased - which is the convention here. I would ensure that fDictionary returns an autoreleased NSDictionary.
Upvotes: 1
Reputation: 52565
Without knowing anything about fDictionary
it's difficult to be sure, but the convention followed in most Object C code is as follows:
alloc
or copy
retain
itIf you don't own it you should not release
it.
So by convention, the function would return an autorelease
d object and you wouldn't need any extra management in your method.
Upvotes: 1
Reputation: 28806
If the function was written properly, the dictionary is autoreleased, so you don't have to release it at all. It will be released soon, by the autorelease pool.
You only release what you yourself retain or copy. These are the things you "own". Be sure not to release them too early. The usual point is before the end of the function they are allocated or retained in, if they are local. If they are ivars, the best point is, usually, the dealloc of the class to which the ivar belongs.
Upvotes: 3