In the commit of UITableView I delete an object using the following code:
[_context deleteObject:[_StudiessList objectAtIndex:indexPath.row]];
NSError *error;
if (![_context save:&error]) {
// Handle error
NSLog(@"Unresolved error series %@, %@", error, [error userInfo]);
}
[self LoadData]; // bad access fire here
where LoadData
is the function to refill the table view
Its code is:
iPaxeraAppDeleg开发者_JS百科ate *appDelegate = (iPaxeraAppDelegate *)[[UIApplication sharedApplication] delegate];
self.context = appDelegate.managedObjectContext;
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription
entityForName:@"Studies" inManagedObjectContext:_context];
[fetchRequest setEntity:entity];
NSArray *sortDescriptors = [NSArray arrayWithObject:[[[NSSortDescriptor alloc] initWithKey:@"StudyDate" ascending:YES] autorelease]];
[fetchRequest setSortDescriptors:sortDescriptors];
NSError *error;
@try {
// error done here exactly at fetch
self.StudiessList = [_context executeFetchRequest:fetchRequest error:&error];
}
@catch (NSException * e) {
NSLog(e);
}
[fetchRequest release];
[StudiessList retain];
LoadData
crashes upon executeFetchRequest:
Your problem is probably here:
NSArray *sortDescriptors = [NSArray arrayWithObject:[[[NSSortDescriptor alloc] initWithKey:@"StudyDate" ascending:YES] autorelease]];
By attaching an explicit autorelease you set up a circumstance in which the sort descriptor may be deallocated while it is still needed. When the fetch goes to grab the sort descriptor, it crashes because the object is not there.
Explicit autoreleases can be problematical because they are intimately linked to the draining of the memory pool of the immediate scope they are defined in. Although many people use autorelease casually, you should really only use it when you are returning a value from a method because autorelease tells, the runtime, "I am completely done with this object and I don't care what happens to it." If you are not done with the object, then you will have problems.
Using an implicit autorelease from a convenience method eliminates this problem because the autorelease is issued in another scope e.g. the class object holding the convenience method. It then enters the local scope and can be retained without having to worry about an autorelease in the local scope killing it.
Try:
NSArray *sortDescriptors = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"StudyDate " ascending:YES]];
... and see if that resolves the crash.
精彩评论