Should I retain, autorelease or do nothing when returning NSArray of executeFetchRequest: result?
Please have a look at the code below:
- (NSArray *)requestEntities:(NSString *)entityName {
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription
entityForName:entityName inManagedObjectContext:_context];
[fetchRequest setEntity:entity];
NSError *requestError = nil;
NSArray *result = [_context executeFetchRequest:fetchRequest error:&requestError];
[fetchReques开发者_Go百科t release], fetchRequest = nil;
return result;
}
and I need to use the result somewhere else, in this method, is result correctly returned(without retain or autorelease)? Also, what should its callers do when getting the result, retain it or use it straight away?
Thanks!
The convention is that you're not responsible for objects returned by methods other than those containing new
, alloc
, or copy
. The array you're given is almost certainly already autoreleased, so it will be released when your code finishes and it goes back to the run loop. If you need to hold onto the array beyond that point (e.g., if you want to keep those results around and refer to them to respond to future UI events) then you should retain the array, preferably by assigning it to a retained property.
I heavily recommend you read the memory management programming guide in full, or at least the first few sections which get right to the meat of what you're asking about.
精彩评论