开发者

Releasing objects created by functions

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 relea开发者_如何学Pythonsing the NSDictionary object.

Should I release it in the method, or autorelease it in the function?


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.


Without knowing anything about fDictionary it's difficult to be sure, but the convention followed in most Object C code is as follows:

  • You own it if the instance was created with an alloc or copy
  • You own it if you retain it
  • Otherwise you don't own it

If you don't own it you should not release it.

So by convention, the function would return an autoreleased object and you wouldn't need any extra management in your method.


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.


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.


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 alloced, 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜