UITableViewの行削除でセクション数が減るとクラッシュする

久々のiPhoneアプリ開発ではまったのでメモ。

行を削除でセクションがなくなるような場合、deleteRowsAtIndexPathsで行を削除しただけでは以下のようなエラーでクラッシュします。


f:id:kaz_29:20120831071434p:plain

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of sections. The number of sections contained in the table view after the update (1) must be equal to the number of sections contained in the table view before the update (2), plus or minus the number of sections inserted or deleted (0 inserted, 0 deleted).'

行の削除によりセクションにデータがなくなるような場合は以下の様にセクションも削除する必要がある様です。

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle 
                                            forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        [tableView beginUpdates];

        // self.tableData = NSMutableArray
        [[self.tableData getObject:[indexPath section]] removeObjectAtIndex:[indexPath row]];
        if ([[self.tableData getObject:[indexPath section]] count] == 0) {
            [self.tableData removeObjectAtIndex:[indexPath section]];
        }

        if ([self.tableData count] != [self.tableView numberOfSections]) {
            [self.tableData removeObjectAtIndex:[indexPath section]];
            [self.tableView deleteSections:[NSIndexSet indexSetWithIndex:[indexPath section]] withRowAnimation:YES];
        }
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];

        [tableView endUpdates];
    }
}
  • 2012/8/31 10:20 サンプルコードに問題があったので微修正。