首页 > 解决方案 > 结果不正确的领域结果对象(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 语句中调试器的屏幕截图:

调试器映像

是否需要更改我使用对象、提取数据等的方式以使对象中的数据正确?

标签: swiftrealmxcode11

解决方案


在这里找到我的答案: 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
    }

我遇到的问题是我一直在拉第一个位置结果对象,而不是一个部分中的第一个位置。我需要缩小到我的部分,然后拉第一行。


推荐阅读