I'm trying to use an alertView to warn users that they are about to delete an object. Here is my code:
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
UIAlertView *alert = [[UIAlertView 开发者_Go百科alloc] initWithTitle:@"Caution!"
message:@"Are you sure you want to delete this truck?"
delegate:self
cancelButtonTitle:@"NO"
otherButtonTitles:@"YES", nil];
[alert show];
[alert release];
} }
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
if (buttonIndex == 1) {
NSIndexPath *indexPath = [truckTableView indexPathForSelectedRow];
NSManagedObjectContext *moc = [self.fetchedResultsController managedObjectContext];
Truck *truck = [fetchedResultsController objectAtIndexPath:indexPath];
[moc deleteObject:truck];
NSError *error = nil;
if (![moc save:&error]) {
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
}
else {
}}
The alert view appears correctly, if I tap "NO" is disappears and all is well. If I tap "YES", the app crashes with no log report, just EXC_BAD_ACCESS. From what I have researched, it's possible that the alertView is releasing before deleting the object? Is this right? If so, then how to I retain the alertView until after the delete has processed? thanks for all your help!
Most likely this is caused because [truckTableView indexPathForSelectedRow]
is nil. And because of this, truck will be nil too. And when you try to delete a "nil object" deleteObject:
will throw an exception
You should save the indexPath of the cell you want to delete as an instance variable.
Often EXC_BAD_ACCESS
comes from accessing a released object, but not this time. It's ok to release the alert after you've showed it.
精彩评论