我在使用UITableView的cellForRowAt正确访问Realm的result对象时遇到了问题。
下面是设置:
UITableViewController根据对象的类别(对象中定义的字符串)划分为多个部分。
UITableViewController有一个到UIViewController的段,它接受表单输入。该视图控制器写入Realm,然后通过委托进行回调以刷新表视图数据。
当屏幕关闭并返回到UITableViewController时,当我尝试通过类别添加行时,我得到的是空对象。但是,当我在cellForRowAt中使用for循环时,我可以访问数据。
以下是我在本节中运行的内容:
func loadItems() {
itemsList = try! Realm().objects(Items.self).filter("list_id = \(list_id)").sorted(byKeyPath: "item_category")
tableView.reloadData()
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "itemListCell", for: indexPath)
let categoryName = categories.categories[indexPath.section]
let currItem = itemsList[indexPath.row]
if currItem.item_category == categoryName {
cell.textLabel!.text = currItem.item_name
}
return cell
}它似乎正确地评估了类别并进入了该块,但对象的item_name和item_category为空。下面是if语句中调试器的屏幕截图:
为了让对象中的数据正确无误,我是否需要在使用对象、拉取数据等方面进行一些更改?
发布于 2019-10-10 23:24:56
我认为这可能与您的过滤器谓词有关。试着改变
itemsList = try! Realm().objects(Items.self).filter("list_id = \(list_id)").sorted(byKeyPath: "item_category"到这个
itemsList = try! Realm().objects(Items.self).filter("list_id = '\(list_id)'").sorted(byKeyPath: "item_category"在'(list_id)‘两边添加单引号。
https://stackoverflow.com/questions/58324798
复制相似问题