ronm nsinternalinconsistencyException启动app脱机时



我正在测试的生命周期是: Start App Online -> Add item -> go offline -> kill the app -> open app -> add item -> go online。如果我尝试在上网后尝试添加新项目,我会得到'NSInternalInconsistencyException', reason: 'attempt to insert row 9 into section 0, but there are only 0 rows in section 0 after the update'不确定为什么它认为第0节中只有0行。

相关代码:

let realm = try! Realm()
let owners = try! Realm().objects(OwnerList.self).first?.list
// Notification token defined in viewDidLoad()
self.notificationToken = self.owners?.addNotificationBlock { [unowned self] changes in
        switch changes {
        case .initial:
            self.tableView.reloadData()
        case .update(_, let deletions, let insertions, let modifications):
            // Query results have changed, so apply them to the UITableView
            self.tableView.beginUpdates()
            self.tableView.insertRows(at: insertions.map { IndexPath(row: $0, section: 0) }, with: .automatic)
            self.tableView.deleteRows(at: deletions.map { IndexPath(row: $0, section: 0) }, with: .automatic)
            self.tableView.reloadRows(at: modifications.map { IndexPath(row: $0, section: 0) }, with: .none)
            self.tableView.endUpdates()
        case .error(let error):
            print("Notification Error", error)
            break
        }
}
// Helper Function when inserting item
func insertItem() throws {
    self.realm.beginWrite()
    let owner = Owner().generate()
    self.owners?.insert(owner, at: (owners?.count)!)
    self.tableView.insertRows(at: [[0, (owners?.count)!-1]], with: .automatic)
    try self.realm.commitWrite(withoutNotifying: [self.notificationToken!])
}

您不应该插入行之前,因为写入交易可能会失败。

尝试移动

self.tableView.insertRows(at: [[0, (owners?.count)!-1]], with: .automatic)

realm.commitWrite(..)

还要确保您的tableview dataSource方法返回正确的值。

弄清楚了,请确保您将tableview委托和datasource设置为 viewDidLoad() not viewWillAppear()

最新更新