Search code examples
iosswiftswift3realmrealm-mobile-platform

Realm NSInternalInconsistencyException When Starting App Offline


The lifecycle I am testing is: Start App Online -> Add item -> go offline -> kill the app -> open app -> add item -> go online. If I try adding a new item after going online I get 'NSInternalInconsistencyException', reason: 'attempt to insert row 9 into section 0, but there are only 0 rows in section 0 after the update' Not sure why it believes there are only 0 rows in section 0.

Relevant Code:

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!])
}

Solution

  • Figured it out, make sure you set your tableview delegate and datasource in viewDidLoad() not viewWillAppear()