Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

To Autorelease or Not to Autorelease

In the following code example from the Core Data Programming Guide, NSFetchRequest is created with autorelease while NSSortDescriptor is not created with autorelease. Why wasn't NSSortDescriptor created with autorelease? Is it a matter of preference?

NSManagedObjectContext *moc = [self managedObjectContext];    
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"Employee" 
                                                     inManagedObjectContext:moc];

NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
[request setEntity:entityDescription];
// Set example predicate and sort orderings...
NSNumber *minimumSalary = ...;
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(lastName LIKE[c]'Worsley') AND (salary > %@)", minimumSalary];    
[request setPredicate:predicate];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"firstName" 
                                                               ascending:YES];
[request setSortDescriptors:[NSArray arrayWithObject:sortDescriptor]];
[sortDescriptor release];
NSError *error;
NSArray *array = [moc executeFetchRequest:request error:&error];
if (array == nil){
    // Deal with error...
}
like image 384
Joo Park Avatar asked Jan 29 '10 22:01

Joo Park


1 Answers

When you autorelease, you're basically saying: "I don't need this any longer, but anyone else is free to pick it up (before the auto release pool is drained)". When you explicitly relase an object you're saying: "I don't need this any longer and unless anyone else has already said otherwise (acquired), it should be deallocated immediately."

Consequently, autorelease is not normally the wrong thing to. It is required when you want to pass objects back to the sender of a message without requiring the sender to take care of releasing the object.

like image 84
VoidPointer Avatar answered Oct 12 '22 14:10

VoidPointer