[英]Row deletion doesn't update table view
我正在将数据加载到UITableViewController中,数据来自Realm。 所以我在ViewController上有一个属性: var nextWeekPlants: Results<Plant>!
。
变量的加载方式如下: nextWeekPlants = realm.objects(Plant.self).filter("...")
在我编写的updateUI()
方法中。 updateUI()
方法还调用tableView.reloadData()
。
在我的numberOfRowsInSection
委托方法中,我进行了以下检查:
if let plants = nextWeekPlants {
return plants.count
} else {
return 0
}
好了,它可以很好地收集数据,并在屏幕上显示出来,但是,一旦我从表格视图中删除1个植物并想要删除另一个植物,它就会崩溃。 'RLMException', reason: 'Index 1 is out of bounds (must be less than 1)'
我以这种方式删除植物:
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()
它可以删除一个植物,但是不会删除另一个。 是否需要以其他方式更新tableView updateUI()
也许调用updateUI()
?)还是需要更新Realm集合?
**编辑**
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()
}
看起来您是在不通知Realm的情况下更改UITableView状态。 请参考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.