领域过滤结果列表中的空对象

时间:2016-11-03 10:21:13

标签: swift realm

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

以下是结果的演示列表:

{
  "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"
    }
}

1 个答案:

答案 0 :(得分:1)

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

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

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