简体   繁体   中英

Row deletion doesn't update table view

I am loading data into a UITableViewController, the data is coming from Realm. So I have a property on my ViewController: var nextWeekPlants: Results<Plant>! .

The variable is loaded like this: nextWeekPlants = realm.objects(Plant.self).filter("...") in the updateUI() method I wrote. The updateUI() method also calls tableView.reloadData() .

In my numberOfRowsInSection delegate method, I have this check:

if let plants = nextWeekPlants {
    return plants.count
} else {
    return 0
}

Alright, it works fine collecting the data, showing it on the screen, but as soon as I remove 1 plant from the table view and want to delete another: it crashes. 'RLMException', reason: 'Index 1 is out of bounds (must be less than 1)'

I delete a plant in this way:

tableView.beginUpdates()
do {
    self.realm.beginWrite()
    self.realm.delete(self.nextWeekPlants[indexPath.row])
    try self.realm.commitWrite()
} catch (let error) {
    print(error.localizedDescription)
}
tableView.deleteRows(at: [indexPath], with: .left)
tableView.endUpdates()

It deletes one plant just fine, but it doesn't delete the other. Do I have to update the tableView in a different way (call updateUI() maybe?) or do I need to update my Realm collection?

** EDIT **

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    // Little hack to show no extra cells and to make sure the swiping works.
    self.tableView.allowsMultipleSelectionDuringEditing = false
    self.tableView.tableFooterView = UIView()

    updateUI()
}

func updateUI() {
    let calendar = Calendar.current
    let maxDate = calendar.date(byAdding: .day, value: 7, to: Date())

    if let nextWeek = maxDate {
         nextWeekPlants = realm.objects(Plant.self).filter("nextWater <= %@", nextWeek)
    }

    self.tableView.setEditing(false, animated: true)
    self.tableView.reloadData()
}

Looks like you're mutating UITableView state without letting Realm know about it. Please refer to the Interface-Driven Writes section of Realm's documentation.

do {
    self.realm.beginWrite()
    self.realm.delete(self.nextWeekPlants[indexPath.row])
    tableView.deleteRows(at: [indexPath], with: .left)
    try self.realm.commitWrite(withoutNotifying: [token])
} catch (let error) {
    print(error.localizedDescription)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM