Подтвердить что ты не робот

'Неверное обновление: недопустимое количество строк в разделе 0

Я прочитал все связанные с этим сообщения, и у меня все еще есть ошибка:

'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).'

Вот подробности:

in .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]);

}

Чтобы включить удаление и удаление объекта из массива:

// 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];


    }
}

Я думал, что, если число моих разделов зависит от количества массива, которое я редактирую, оно обеспечит правильное количество строк? Не удается ли это сделать, не перезагружая таблицу, когда вы все равно удаляете строку?

4b9b3361

Ответ 1

Вам нужно удалить объект из массива данных, прежде чем вы вызовете 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];

Ответ 2

Swift Version → Удалить объект из массива данных перед вызовом

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
    if editingStyle == .delete {
        print("Deleted")

        currentCart.remove(at: indexPath.row) //Remove element from your array 
        self.tableView.deleteRows(at: [indexPath], with: .automatic)
    }
}

Ответ 3

В моем случае проблема заключалась в том, что numberOfRowsInSection возвращал одинаковое количество строк после вызова tableView.deleteRows(...).

Поскольку в моем случае это было обязательным поведением, я в итоге вызвал tableView.reloadData() вместо tableView.deleteRows(...) в тех случаях, когда numberOfRowsInSection останется таким же после удаления строки.