iPhone: Return NSMutableArray in method while still releasing

余生长醉 提交于 2019-12-07 07:34:27

You should autorelease, like you said. The caller probably needs to retain, like this - especially if storing into an instance variable:

NSMutableArray *array = [[obj getData] retain];

Later, when it's totally done with it:

[array release]; // balances the retain above

You're on the right track. You should pair every alloc/init with either release or autorelease, which will cause the object to get cleaned up as soon as the final reference to it goes away.

The pattern is something like this:

- (SomeObject*)generateSomeObject
{
    SomeObject* someObject = [[[SomeObject alloc] init] autorelease];
    ...
    return someObject;
}

Are you assigning the result of this method to an instance variable? Keep in mind that things that added to the autorelease pool are released at some point in the future (usually at the end of the run loop), so if you assign it to an instance variable, and the end of the run loop comes around, your instance variable will end up pointing to garbage (or sometimes a different object) unless you retain it.

The name of the method (getData) would suggest that the object being returned should be autoreleased, so you can create the array with [NSMutableArray array], fill it up as per usual, and then return it from the method.

If the code that invokes getData wants the array to survive an iteration of the run loop, it needs to retain it, but also, it needs to make sure to release the array when it's finally finished with it — this is usually done in your dealloc method.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!