【发布时间】:2017-07-09 19:19:11
【问题描述】:
我正在将数据加载到 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()?)还是我需要更新我的 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()
}
【问题讨论】:
-
在结束更新之前尝试 reloadData(),同时从 nextWeekPlants 中删除该对象
-
@jbehrens94 我猜你也需要更新表数组值。植物数组。
-
@RJiryes 这将更新 tableView 两次,我想这不是很好的 UI。 @TusharSharma 所以也许我需要再次调用
updateUI(),因为该方法设置了领域集合属性? -
能否请在您调用
updateUI()的地方添加代码? -
是的,只需更新 nextWeekPlants 属性 :-)
标签: ios uitableview swift3 realm