问题描述
在以下核心数据编程指南的代码示例中,NSFetchRequest使用autorelease创建
,而NSSortDescriptor不使用autorelease创建。为什么不使用autorelease创建NSSortDescriptor?这是一个偏好问题吗?
In the following code example from the Core Data Programming Guide, NSFetchRequest is createdwith 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...
}
推荐答案
当你自动发布时,你基本上是在说:我不再需要这个了,但其他任何人都可以随意拿起它(在此之前)自动释放池已耗尽)。当您明确地重新发送一个对象时,您说:我不再需要这个,除非其他人已经说过(获得),否则应该立即解除分配。
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.
这篇关于自动释放或不自动释放的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!