【问题标题】:Realm results object with incorrect results (iOS, Swift)结果不正确的领域结果对象(iOS,Swift)
【发布时间】:2019-10-10 14:02:53
【问题描述】:

我在使用 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 语句中调试器的截图:

Debugger Image

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

【问题讨论】:

    标签: swift realm xcode11


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

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

      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

      【讨论】:

      • 实际上,在这里找到了答案:*.com/questions/38728938/… 看起来我需要在 cellForRowAt 的部分类别中进行过滤,然后拉出 indexPath.row。问题是我有一个二维数组,但无论如何总是将 indexPath 拉到 0。这把我搞砸了。
      • @bwor80 如果您找到了答案并有一些工作代码,请将其作为答案包含在您的代码中,以便帮助其他人!