/ /削除し、UITableView行を追加する - objective-c、uitableview、ios7

削除し、UITableView行を追加する - objective-c、uitableview、ios7

私のアプリケーションでは、私が指定するUITableViewがあります - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 150行あります。今、私のデータソースNSArrayは150以上の要素を持っているので、期待通りに、私のテーブルは最初の150を表示します。私も実装しました - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath ユーザーは要素を削除することができますUITableView。ユーザーが行を削除すると、削除された行が消えて(アニメーションで)、残りの行が上に移動し、以前にはなかったデータソース配列の151番目の要素が表示されます表示され、テーブルの最後の要素として表示されます。しかし、私がこれまでに試したことは、私に次のエラーを与えました:

Terminating app due to uncaught exception "NSInternalInconsistencyException", reason: "Invalid update: invalid number of rows in section 0.  The number of rows contained in an existing section after the update (150) must be equal to the number of rows contained in that section before the update (150), plus or minus the number of rows inserted or deleted from that section (0 inserted, 1 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out)."
First throw call stack:
(0x2e58fecb 0x38d2ace7 0x2e58fd9d 0x2ef3de2f 0x30f94761 0x30ff0f7f 0x2af0f49 0xdf763 0x30fba567 0x30fba4f9 0x30df66a7 0x30df6643 0x30df6613 0x30de1d5b 0x30df605b 0x30db9521 0x30df1305 0x30df0c2b 0x30dc5e55 0x30dc4521 0x2e55afaf 0x2e55a477 0x2e558c67 0x2e4c3729 0x2e4c350b 0x334326d3 0x30e24871 0x106b59 0x39228ab7)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)

次のコードは、これを実装する方法の要点を説明しています。

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {

if (editingStyle == UITableViewCellEditingStyleDelete) {

PNObject *objectToDelete = contentArray[indexPath.row];
NSMutableArray *mutableCopy = [contentArray mutableCopy];
[mutableCopy removeObject:objectToDelete];
[tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}
}

回答:

回答№1は1

まだ関係のある仲間かどうかは分からないが、
しかし、私が考えているのは、実際にデータソースを更新しないということです。

データソースの「ローカル」可変コピーを作成し、そのコピー内のオブジェクトを削除していますが、実際のデータソースは同じままで、削除するアイテムが含まれています。

私はあなたのことを推測しています numberOfRows:inSection: いくつかのバリエーションを含んでいます [contentArray count]

だから、あなたがテーブルビューからアイテムを「削除」しているので、あなたのアプリはそのテーブルビューにアイテムが1つ少ないことを除いて、
しかし、テーブルビューのコンテンツを再読み込みするとき、アイテムがデータソースから削除されていないため、テーブルビューには予想よりも1つ多くの項目があります。

これを解決するには、contentArrayをNSMutableArrayに変更し、
上記のコードで、 objectToDelete そこから直接。
次に、オブジェクトへのローカル参照を作成せずに、オブジェクトを配列から直接削除することもできます。 したがって、上記のコードは次のようになります。

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {

if (editingStyle == UITableViewCellEditingStyleDelete) {

[contentArray removeObjectAtIndex:indexPath.row];
[tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}
}