离线启动应用程序时出现领域 NSInternalInconsistencyException

Realm NSInternalInconsistencyException When Starting App Offline

我正在测试的生命周期是: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: [=10=], section: 0) }, with: .automatic)
            self.tableView.deleteRows(at: deletions.map { IndexPath(row: [=10=], section: 0) }, with: .automatic)
            self.tableView.reloadRows(at: modifications.map { IndexPath(row: [=10=], 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 数据源方法 return 正确的值。

搞清楚了,确保在 viewDidLoad() 而不是 viewWillAppear()

中设置 tableview 委托和数据源