我正在测试的生命周期是: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!])
}
答案 0 :(得分:1)
在提交写入事务之前不应插入行,因为写入事务可能会失败。
尝试移动
self.tableView.insertRows(at: [[0, (owners?.count)!-1]], with: .automatic)
在realm.commitWrite(..)
之后。
还要确保tableview数据源方法返回正确的值。
答案 1 :(得分:0)
想出来,确保在viewDidLoad()
而不是viewWillAppear()