获取“ NSInternalInconsistencyException”,在插入和删除时,第0节中的无效行数错误?

时间:2019-07-23 06:44:56

标签: swift xcode uitableview

尝试插入行时,tableview崩溃,并显示“无效更新:第0节中的行数无效。更新(1)之后现有节中包含的行数必须等于行数该部分包含在更新(0)之前,加上或减去从该部分插入或删除的行数(已插入0,已删除0),以及加上或减去移入或移出该部分的行数(移入0) ,0移出)。'“ 当我尝试删除行行“尝试将第0行插入第0节,但更新后第0节中只有0行”时,它也会崩溃。

这是从Github克隆的一个名为antidote的SDK。仅使用tableview.reloaddata()而不是开始和结束更新,反之亦然。

相同的链接是:https://github.com/Antidote-for-Tox/Antidote

FriendListController

super.viewDidLoad()

    let friends = submanagerObjects.friends()
    let requests = submanagerObjects.friendRequests()
    dataSource = FriendListDataSource(theme: theme, friends: 
friends, requests: requests)
    dataSource.delegate = self

    tableView.tableFooterView = UIView()

    updateViewsVisibility()
}

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    updateViewsVisibility()
}

extension FriendListController: FriendListDataSourceDelegate {

    func friendListDataSourceBeginUpdates() {
        tableView.beginUpdates()
    }

    func friendListDataSourceEndUpdates() {
        tableView.endUpdates()
        updateViewsVisibility()
    }

    func friendListDataSourceInsertRowsAtIndexPaths(_ indexPaths: [IndexPath]) {
        tableView.insertRows(at: indexPaths, with: .automatic)
    }

    func friendListDataSourceDeleteRowsAtIndexPaths(_ indexPaths: [IndexPath]) {
        tableView.deleteRows(at: indexPaths, with: .automatic)
    }

    func friendListDataSourceReloadRowsAtIndexPaths(_ indexPaths: [IndexPath]) {
        tableView.reloadRows(at: indexPaths, with: .automatic)
    }

    func friendListDataSourceInsertSections(_ sections: IndexSet) {
        tableView.insertSections(sections, with: .automatic)
    }

    func friendListDataSourceDeleteSections(_ sections: IndexSet) {
        tableView.deleteSections(sections, with: .automatic)
    }

    func friendListDataSourceReloadSections(_ sections: IndexSet) {
        tableView.reloadSections(sections, with: .automatic)
    }

    func friendListDataSourceReloadTable() {
        tableView.reloadData()
    }
}

extension FriendListController: UITableViewDataSource {

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: FriendListCell.staticReuseIdentifier) as! FriendListCell
        let model = dataSource.modelAtIndexPath(indexPath)

        cell.setupWithTheme(theme, model: model)

        return cell
    }

    func numberOfSections(in tableView: UITableView) -> Int {
        return dataSource.numberOfSections()
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataSource.numberOfRowsInSection(section)
    }

    func sectionIndexTitles(for tableView: UITableView) -> [String]? {
        return dataSource.sectionIndexTitles()
    }

    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return dataSource.titleForHeaderInSection(section)
    }

    func tableView(_ tableView: UITableView, commit editingStyle: 
UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            let title: String

            switch dataSource.objectAtIndexPath(indexPath) {
            case .request:
                title = String(localized:"delete_contact_request_title")
            case .friend:
                title = String(localized:"delete_contact_title")
            }

            let alert = UIAlertController(title: title, message: nil, preferredStyle: .alert)

            alert.addAction(UIAlertAction(title: String(localized: "alert_cancel"), style: .default, handler: nil))
            alert.addAction(UIAlertAction(title: String(localized: "alert_delete"), style: .destructive) { [unowned self] _ -> Void in

                switch self.dataSource.objectAtIndexPath(indexPath) {
                case .request(let request):
                    self.submanagerFriends.remove(request)
                case .friend(let friend):
                    do {
                        let chat = 
 self.submanagerChats.getOrCreateChat(with: friend)

                        try self.submanagerFriends.remove(friend)
                        self.submanagerChats.removeAllMessages(in: chat, removeChat: true)
                    } catch let error as NSError {
                             handleErrorWithType(.removeFriend, error: error)
                        }
                 }
            })

            present(alert, animated: true, completion: nil)
        }
    }
}

FriendListDataSource

private extension FriendListDataSource {

    func addNotificationBlocks() {
        requestsToken = requests?.addNotificationBlock { [unowned self] change in
        switch change {
        case .initial:
            break
        case .update(let requests, let deletions, let insertions, let modifications):
            guard let requests = requests else { return }
            if deletions.count > 0 {
                self.delegate?.friendListDataSourceReloadTable()
                return
            }
            self.delegate?.friendListDataSourceBeginUpdates()

            let countAfter = requests.count
            let countBefore = countAfter - insertions.count + deletions.count

            if countBefore == 0 && countAfter > 0 {
                self.delegate?.friendListDataSourceInsertSections(IndexSet(integer: 0))
            } else { 
                    self.delegate?.friendListDataSourceDeleteRowsAtIndexPaths(deletions.map { IndexPath(row: $0, section: 0)} )
                    self.delegate?.friendListDataSourceInsertRowsAtIndexPaths(insertions.map { IndexPath(row: $0, section: 0)} )
                    self.delegate?.friendListDataSourceReloadRowsAtIndexPaths(modifications.map { IndexPath(row: $0, section: 0)} )  
                }
                 self.delegate?.friendListDataSourceEndUpdates()
        case .error(let error):
            fatalError("\(error)")
        }
    }

它应该能正常工作,而不会在插入和删除时崩溃,前者会产生“无效更新:第0节中的行数无效。更新(1)后现有节中包含的行数必须为等于更新之前该部分中包含的行数(0),加上或减去从该部分中插入或删除的行数(插入0,删除0),以及加上或减去移入或移出的行数该部分(移入0,移出0)。”“ 后者产生:“'试图将第0行插入第0节,但更新后第0节只有0行。'“

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

根据enter image description here类,您必须使用以下之一:

  • performBatchUpdates(_:completion:)UITableView
  • func beginUpdates()link),然后是func endUpdates()link

您必须在批处理更新块之内(或在开始和结束更新功能之间)执行所有更新(包括数据源更新-不仅是插入/删除/移动/重新加载)< / p>

这样可以避免崩溃。

例如:

var dataSource: [Int] = [1, 2, 3]

tableView.beginUpdates()
dataSource.append(4)
tableView.insertRows(at: [IndexPath(row: 3, section: 0)], with: .automatic)
tableView.endUpdates()