1
我的應用程序使用Core Data託管的表視圖,我在cimgf.com上的一些好人幫助下實現了一個重新排序內容的方法。 在這樣做之前,我能夠通過使用下面的代碼很容易地刪除對象:從Core Data managet中刪除對象時出錯表視圖
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
[self.tableView beginUpdates]; // Avoid NSInternalInconsistencyException
// Delete the person object that was swiped
Step *stepToDelete = [self.fetchedResultsController objectAtIndexPath:indexPath];
NSLog(@"Deleting (%@)", stepToDelete.name);
[self.managedObjectContext deleteObject:stepToDelete];
[self.managedObjectContext save:nil];
// Delete the (now empty) row on the table
[self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
[self performFetch];
[self.tableView endUpdates];
[delegate stepChangedOnMaster:self];
}
}
添加下面的代碼,當一個對象被刪除,應用程序崩潰之後。
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
return YES;
}
- (void)tableView:(UITableView *)tableView
moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath
toIndexPath:(NSIndexPath *)destinationIndexPath;
{
NSMutableArray *things = [[__fetchedResultsController fetchedObjects] mutableCopy];
// Grab the item we're moving.
NSManagedObject *thing = [[self fetchedResultsController] objectAtIndexPath:sourceIndexPath];
// Remove the object we're moving from the array.
[things removeObject:thing];
// Now re-insert it at the destination.
[things insertObject:thing atIndex:[destinationIndexPath row]];
// All of the objects are now in their correct order. Update each
// object's displayOrder field by iterating through the array.
int i = 0;
for (NSManagedObject *mo in things)
{
NSLog(@"%i - %@", i, [mo valueForKey:@"name"]);
[mo setValue:[NSNumber numberWithInt:i++] forKey:@"displayOrder"];
}
things = nil;
[__managedObjectContext save:nil];
// Save
NSError *error = nil;
if (![__managedObjectContext save:&error])
{
NSString *msg = @"An error occurred when attempting to save your user profile changes.\nThe application needs to quit.";
NSString *details = [NSString stringWithFormat:@"%@ %s: %@", [self class], _cmd, [error userInfo]];
NSLog(@"%@\n\nDetails: %@", msg, details);
}
// re-do the fetch so that the underlying cache of objects will be sorted
// correctly
NSError *errror = nil;
if (![__fetchedResultsController performFetch:&errror])
{
NSLog(@"Unresolved error %@, %@", errror, [errror userInfo]);
abort();
}
[self.tableView reloadData];
}
我真的不明白爲什麼應用程序崩潰。有人可以給我一些關於如何解決這個問題的提示嗎?謝謝!
這是錯誤我得到: *終止應用程序由於未捕獲的異常「NSInternalInconsistencyException」,理由是:「無效的更新:在第0無效的行數後包含在現有的部分的行數update(0)必須等於更新前(1)的該部分中包含的行數,加上或減去從該部分插入或刪除的行數(0插入,2刪除)和正數或負數行移入或移出該部分(0移入,0移出)。' *
調試控制檯提供的關於崩潰的內容是什麼?應該有某種消息或其他。如果您設置了一個異常斷點,那麼在顯示錯誤消息之前,您可能需要按一次或兩次「coninue」。 – 2013-02-18 11:43:26
用錯誤更新了問題 – 2013-02-18 12:43:47