结果不正确的领域结果对象(iOS、Swift)

Realm results object with incorrect results (iOS, Swift)

我在使用 UITableView 的 cellForRowAt 正确访问 Realm 的结果对象时遇到问题。

设置如下:

UITableViewController 根据对象的类别(对象中定义的字符串)分为多个部分。

UITableViewController 与接受表单输入的 UIViewController 有一个 segue。该视图控制器写入 Realm,然后通过委托进行回调以刷新 table 视图数据。

当该屏幕关闭并 returns 到 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 语句中调试器的屏幕截图:

Debugger Image

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

我认为这可能与您的过滤器谓词有关。尝试改变

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)”周围添加单引号。

Realm Filtering

在这里找到我的答案:

这是我对 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
    }

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