开发者

iOS correct way (memory management) for a method to return a value

If I have a class named Foo and I have this function + getIds that should return ids. Would the correct signature of + getIds look like this:

+ (NSArray *)getIds {

    NSMutab开发者_JAVA技巧leArray *ids = [[[NSMutableArray alloc] init] autorelease];

    return ids;
}

What I'm wondering is that if I should use autorelease on *ids? There is no other way I assume? I can't do [ids release] after the return statement right?


You can send autorelease message along with alloc, init messages. You can also do, return [ids autorelease]; Note: You should not do both at the same time ;-)

You can not return [id release], because release method itself returns nothing.


The typically-correct memory management for returned objects is to have the called method set it as an autoreleased object, except when the method name contains "copy", "new" or "alloc". In those cases (copy/new/alloc), the returned object is retained, and the caller owns it (i.e. the caller is responsible for making sure they are released).

The code you wrote in the question will do the correct thing - it will return an autoreleased object.

When the caller gets the NSArray back, they can use the object as much as they like, and if they don't need the object in future calls, then they don't need to do any extra memory management. At the end of the run loop, the NSArray will be released, which is the desired behavior. If the caller does need the object to live longer, then they have to call retain on it (or something equivalent to that, such as calling something else that calls retain on it), and then they take the responsibility to call release on it later.

Useful stuff:

  • Apple's iOS memory management guide
  • My personal memory management guidelines (shorter, more biased)
  • Understanding run loops

Also, this will all go away when ARC (automatic reference counting, in iOS 5) becomes the norm.


You are already autoreleasing the array, so calling autorelease a second time would be an error that might result in a crash. The fact that you can't do a release after the return (you've left the function by then) is one of the reasons autorelease exists.

About whether the method should return an autoreleased as opposed to a retained object: Only methods that start with alloc or new or contain copy (as in mutableCopy) shall return retained objects. All other method shall return autoreleased objects.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜