1. ホーム
  2. ios

'無効なアップデート:セクション0の行数が無効です。

2023-10-21 14:12:11

質問

この件に関する関連記事をすべて読みましたが、まだエラーが発生しています。

'Invalid update: invalid number of rows in section 0.  The number of rows contained in an existing section after the update (5) must be equal to the number of rows contained in that section before the update (5), 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).'

以下はその詳細です。

.h 私は NSMutableArray :

@property (strong,nonatomic) NSMutableArray *currentCart;

.m 私の numberOfRowsInSection はこのようになります。

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.


    return ([currentCart count]);

}

deleteを有効にし、配列からオブジェクトを削除する。

// Editing of rows is enabled
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {

        //when delete is tapped
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];

        [currentCart removeObjectAtIndex:indexPath.row];


    }
}

セクションの数を編集中の配列の数に依存させることで、適切な行数を確保できると思ったのですが?これは、とにかく行を削除するときにテーブルを再ロードすることなく行うことができませんか?

どのように解決するのですか?

データ配列からオブジェクトを削除する必要があります。 前に を呼び出す前に deleteRowsAtIndexPaths:withRowAnimation: . ですから、あなたのコードは次のようになります。

// Editing of rows is enabled
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {

        //when delete is tapped
        [currentCart removeObjectAtIndex:indexPath.row];

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

また、配列作成のショートカットである @[] :

[tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];