swift - 结果不正确的领域结果对象(iOS,Swift)
问题描述
我在使用 UITableView 的 cellForRowAt 正确访问 Realm 的结果对象时遇到问题。
这是设置:
UITableViewController 根据对象的类别(对象中定义的字符串)分为多个部分。
UITableViewController 与接受表单输入的 UIViewController 有一个 segue。该视图控制器写入 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 语句中调试器的屏幕截图:
是否需要更改我使用对象、提取数据等的方式以使对象中的数据正确?
解决方案
在这里找到我的答案: UITableView with Multiple Sections using Realm and Swift
这是我对 cellForRowAt 所做的更改:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "itemListCell", for: indexPath)
let currItem = itemsList.filter("item_category = '\(categories[indexPath.section])'")[indexPath.row]
cell.textLabel!.text = currItem.item_name
return cell
}
我遇到的问题是我一直在拉第一个位置结果对象,而不是一个部分中的第一个位置。我需要缩小到我的部分,然后拉第一行。
推荐阅读
- django - 如何在模板中使子菜单动态化?
- amazon-web-services - Terraform 配置 LB 属性失败
- laravel - 如果客户端被撤销,Laravel 护照不会重定向到回调
- python - 获取用户输入后,如何在 selenium 中使 Firefox 无头?
- powershell - 如何在另一台机器的 powershell 中启动一个进程?
- java - 如何管理容器化应用程序设置?
- excel - 有效日期在 Excel 中更改为自定义格式
- sql - 检查一列中的 ID' 在同一张表的另一列中是否没有特定值
- types - DataWeave“作为数字”产生一个对象
- angular - Angular 7 - 发射器和轮询器(调用两次)