简体   繁体   English

行删除不会更新表视图

[英]Row deletion doesn't update table view

I am loading data into a UITableViewController, the data is coming from Realm. 我正在将数据加载到UITableViewController中,数据来自Realm。 So I have a property on my ViewController: var nextWeekPlants: Results<Plant>! 所以我在ViewController上有一个属性: var nextWeekPlants: Results<Plant>! .

The variable is loaded like this: nextWeekPlants = realm.objects(Plant.self).filter("...") in the updateUI() method I wrote. 变量的加载方式如下: nextWeekPlants = realm.objects(Plant.self).filter("...")在我编写的updateUI()方法中。 The updateUI() method also calls tableView.reloadData() . updateUI()方法还调用tableView.reloadData()

In my numberOfRowsInSection delegate method, I have this check: 在我的numberOfRowsInSection委托方法中,我进行了以下检查:

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. 好了,它可以很好地收集数据,并在屏幕上显示出来,但是,一旦我从表格视图中删除1个植物并想要删除另一个植物,它就会崩溃。 '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? 是否需要以其他方式更新tableView updateUI()也许调用updateUI() ?)还是需要更新Realm集合?

** 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. 看起来您是在不通知Realm的情况下更改UITableView状态。 Please refer to the Interface-Driven Writes section of Realm's documentation. 请参考Realm文档的“ 接口驱动的写入”部分。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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