问题
I am trying to understand a little more about memory management. Knowing that I need to release anything that I have init or alloc'ed I am confused about the following:
- (NSMutableArray *)getData {
NSMutableArray *data = [[NSMutableArray alloc] init];
NSString *first = @"First object";
[data addObject:first];
NSString *second = @"Second object";
[data addObject:second];
return data;
}
Since I used alloc and init, I know I need to release my data object. But if I add autorelease to the init part or to the return, it crashes when I run the method.
What is the correct way to do something like this with correct memory management for iPhone?
回答1:
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
回答2:
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;
}
回答3:
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.
来源:https://stackoverflow.com/questions/3835464/iphone-return-nsmutablearray-in-method-while-still-releasing