0

我正在测试的生命周期是: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!])
}
4

2 回答 2

1

在提交写入事务之前不应插入行,因为写入事务可能会失败。

尝试移动

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

之后realm.commitWrite(..)

还要确保您的 tableview 数据源方法返回正确的值。

于 2016-11-29T10:14:19.823 回答
0

想通了,请确保您将 tableview 委托和数据源设置为viewDidLoad()notviewWillAppear()

于 2016-11-29T15:50:20.917 回答