2011-12-05 33 views
1

我試圖使用Apple Table View Programming Guide中所述的標準編輯控件樣式來實現標準的UITableViewCell刪除。當下面的代碼執行在commitEditingStyle方法爲什麼UITableView行被刪除時發生錯誤?

[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]; 

我得到以下錯誤消息

終止應用程序由於未捕獲的異常「NSInternalInconsistencyException」,原因:「無效更新:在第2行的無效數。在更新(1)之後,現有節中包含的行數必須等於更新前(1)節中包含的行數,加上或減去從該節插入或刪除的行數(0插入,1刪除)。

回答

2

如果它是唯一排,我建議你刪除部分也是如此。您還需要將數據源與表同步,即刪除數據源中的行。

這裏有一個正確的例子,當文件系統是iOS中您的數據源:

// Override to support editing the table view. 
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    if (editingStyle == UITableViewCellEditingStyleDelete) { 
    // Delete the row from the data source. 
     File *file = (File *)[self.files objectAtIndex:indexPath.row]; 
     [[NSFileManager defaultManager] removeItemAtPath:file.path error:nil]; 
     [self.files removeObject:file]; 
     if (indexPath.row == 0 && [self.files count] == 0) { 
      NSInteger sectionIndex = [indexPath indexAtPosition:0]; 
      [tableView deleteSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade]; 
     }else { 
      [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]; 
     } 
     [self setupData]; 
    } else if (editingStyle == UITableViewCellEditingStyleInsert) { 
    // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view. 
    } 
} 
+0

沒有什麼錯的空白部分。 Tom Irving指出的問題是單獨更新數據模型以適應已刪除的項目。 – jbat100

+0

處理刪除最後一行的乾淨正確的方法是刪除該部分。我的回答是對OP最完整和有幫助的。這裏有很多很好的例子,包括我自己開發的經驗。這裏是一個StackOverflow演示一個案例(18 upvotes): http://stackoverflow.com/a/1265050/230571 –

+0

無論你想保留空白部分或完全刪除部分是一個偏好問題。如果這是必需的(無論是由開發人員或客戶),那麼這就是你如何做到這一點,我不在乎多少上漲。 – jbat100

4

你要刪除的對象將小區從數據源代表以及消除細胞:

[myObjectsArray removeObjectAtIndex:indexPath.row]; 
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];