【问题标题】:Filtering on RealmOptional removes values of nil, while CoreData predicate does not过滤 RealmOptional 会删除 nil 的值,而 CoreData 谓词不会
【发布时间】:2016-03-09 15:43:19
【问题描述】:

我已将代码从 CoreData 移植到 Realm,除了 1 个最终问题外,一切都运行良好。

使用 RealmOptional 时的过滤是删除所有值等于 nil 的对象。

例如,.filter("price <= 10.0") 正在从结果集中删除所有价格为 nil 的对象。在使用 NSFetchedResultsController 和 NSPredicates 时,CoreData 中没有发生这种行为,所以我想知道这是否是 Realm 的预期行为?

对象如下例中的RealmOptional<Double>

class Product : Object, Mapper
{
    var price = RealmOptional<Double>() {
        // Using ObjectMapper library to map JSON to Realm hence willSet
        willSet {
            self.price = newValue
        }
    }
}

我希望结果返回所有价格 Products,包括那些具有 nil 值的。

这是预期的行为还是只是一个错误?

【问题讨论】:

  • 嗨!来自Realm的Marius。您能否详细说明示例代码中的注释?这看起来很像一个黑客,我看到这可能导致意外行为的危险,但我想了解是什么让你首先想到这个想法。
  • 嗨马吕斯。我正在从 Core Data 移植将 JSON 响应映射到实体模型的代码。我找到了 ObjectMapper 库,但在使用可选值时遇到了困难,因为我无法将项目映射到 let 变量。 Lists 也有类似的问题。我相信我遵循的代码在这里github.com/Hearst-DD/ObjectMapper/issues/143

标签: ios swift core-data realm


【解决方案1】:

如果您按数字比较运算符过滤,则不包括具有空值的对象是预期的行为。如果您想包含pricenil 的对象,可以添加OR price = nil。像下面这样:

let free_or_cheap_products = realm.objects(Product)
    .filter("product <= 10 || product = nil")

【讨论】:

    猜你喜欢
    • 2017-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-29
    • 1970-01-01
    相关资源
    最近更新 更多