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?
You should autorelease, like you said. The caller probably needs to retain, like this – especially if storing into an instance variable:
Later, when it’s totally done with it: