NSException при удалении UITableViewCell

Я использую библиотеку с открытым исходным кодом на Github MGSwipeTableCell (https://github.com/MortimerGoro/MGSwipeTableCell) для отображения кнопок при смахивании ячеек табличного представления.

Сбой происходит, когда я нажимаю кнопку, показанную смахиванием. Я определяю закрытие, которое должно вызываться при нажатии кнопки здесь:

// This is in the library delegate method:
// func swipeTableCell(_ cell: MGSwipeTableCell, swipeButtonsFor direction: MGSwipeDirection, swipeSettings: MGSwipeSettings, expansionSettings: MGSwipeExpansionSettings) -> [UIView]?

// local variables: buttons, one of which is:
let rejectFriendReqButton = MGSwipeButton(title: "", icon: UIImage(named: "X"), backgroundColor: RED) { (cell) -> Bool in

    DispatchQueue.main.async(execute: {
        self.friendListTableView.deleteRows(at: [self.friendListTableView.indexPath(for: cell)!], with: .fade)
    })

    return FriendingCloudKitUtils.declineFriendRequest()
}

// In an if-else ladder:
else if direction == MGSwipeDirection.rightToLeft { // reject friend request

    if section == 2 { // friend requests

        if direction == MGSwipeDirection.leftToRight { // accept friend request
            return [acceptFriendReqButton]
        }

        else if direction == MGSwipeDirection.rightToLeft { // reject friend request

            return [rejectFriendReqButton]
        }
    }
    else if self.friendListTableView.indexPath(for: cell)?.section == 4 { // in friend section
        return [unfriendButton]
    }
}

Сбой происходит на линии, где я звоню deleteRows. Я получаю NSException. Когда я выполняю po $arg1 в lldb, я получаю:

error: Couldn't materialize: couldn't read the value of register x0
error: errored out in DoExecute, couldn't PrepareToExecuteJITExpression

Я пробовал больше возможных решений, чем могу уследить, среди них сохранение кнопки в качестве глобальной переменной, а не локальной.

Другие потенциально важные примечания:

Когда я перехожу в режим отладки, таблица действительно существует:

<UITableView: 0x10186c000; frame = (0 0; 375 554); clipsToBounds = YES; autoresize = RM+BM; gestureRecognizers = <NSArray: 0x17425a760>; layer = <CALayer: 0x174236760>; contentOffset: {0, 0}; contentSize: {375, 357.5}>

Разворачиваемый indexPath также не нулевой и имеет правильные номера разделов и строк:

lldb) po self.friendListTableView.indexPath(for: cell)!
▿ 2 elements
  - 0 : 2
  - 1 : 0

Любые идеи о том, что вызывает это NSException и как я могу это исправить?


person mlecoz    schedule 18.12.2017    source источник


Ответы (2)


    self.friendListTableView.beginUpdates()
    your_dataSource.remove(at: self.friendListTableView.indexPath(for: cell)!)
    self.friendListTableView.deleteRows(at: [self.friendListTableView.indexPath(for: cell)!])
    self.tableView.endUpdates()

Чтобы удалить строку из tableView с анимацией, сначала измените источник данных, а затем вызовите deleteRows. Наконец, заверните код удаления в beginUpdates и endUpdates.

person Sandeep Bhandari    schedule 18.12.2017

Если вы хотите удалить строку, просто найдите значение indexPath этой строки и вызовите этот метод

 func tableView(_ tableView: UITableView, commit editingStyle: 
               UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {    

  if editingStyle == .delete {
       print("Deleted")
      your_dataSource.remove(at: indexPath.row)
      self.tableView.deleteRows(at: [indexPath], with: .automatic)
  }
 }

Он будет обрабатывать вашу операцию удаления строки.

person Masum Biswas    schedule 18.12.2017
comment
Я не думаю, что это необходимо для этой библиотеки. В демоверсии не используются типичные методы делегата табличного представления: >github.com/MortimerGoro/MGSwipeTableCell/blob/master/demo/ - person mlecoz; 19.12.2017