【问题标题】:Realm filter empty objects in a list of Results领域过滤结果列表中的空对象
【发布时间】:2016-11-03 10:21:13
【问题描述】:

如果id 为 nil 或为空,我想过滤领域结果列表。

这是一个演示结果列表:

{
  "id":"1"
  "name": "first"
},
{
  "id":"2"
  "name": "second"
},
{
  "id":"3"
  "name": "third"
},
{
  "id":"" //here it can be empty
  "name": ""
},
{
  "id": nil // here it can be nil
  "name": nil
}

我尝试使用这样的 id 进行过滤,但它崩溃了:

 lazy var declarations: Results<Declaration> = {
        let realm = try! Realm()
        return self.realm.objects(Declaration.self).filter("id == " "")
    }()

这是模型:

import RealmSwift

public final class Declaration: Object {
    dynamic var id: String = ""
    dynamic var name: String = ""

    override public static func primaryKey() -> String? {
        return "id"
    }
}

【问题讨论】:

    标签: swift realm


    【解决方案1】:

    .filter("id == " "") 肯定会崩溃,因为您没有逃脱这些引号。它可能需要.filter("id == \"\""),但只使用单引号会更好。

    由于 Realm 查询符合 NSPredicate,从 this question 复制答案,如果您想简单地检查 Realm 属性是否为空或 nil,您应该能够使用查询

    lazy var declarations: Results<Declaration> = {
        let realm = try! Realm()
        return self.realm.objects(Declaration.self).filter("id != nil AND id != ''")
    }()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-09-08
      • 1970-01-01
      • 1970-01-01
      • 2016-11-02
      • 1970-01-01
      • 2018-10-26
      • 1970-01-01
      相关资源
      最近更新 更多