如何过滤多个变量,其中一个变量是Swift中的Date?

时间:2017-09-05 10:50:00

标签: ios swift realm

Realm版本 - > 2.10

Swift版本> 3

var uuid: String
var resolutionID: Int
var dateFrom: Date

...

我检查过变量不为空。 我试过了:

realm.objects(DeviceDataRealm.self).filter("device.uuid == '\(uuid)' AND resolution.idResolution == \(resolutionID) AND time > \(dateFrom)")

它不起作用......

我也试过了NSPredicate

let predicate = NSPredicate(format: "device.uuid = %@ AND resolution.idResolution = %@ AND time > %@", uuid, resolutionID, dateFrom as CVarArg)
realm.objects(DeviceDataRealm.self).filter(predicate)

仅在没有Date变量的情况下才有效:

realm.objects(DeviceDataRealm.self).filter("device.uuid == '\(uuid)' AND resolution.idResolution == \(resolutionID))

任何想法??

感谢。

1 个答案:

答案 0 :(得分:2)

使用谓词时,您不应该将变量值嵌入谓词中,因为这通常会导致问题,但应使用谓词中的%@并在谓词后面写入变量名称。

然而,问题在于混淆比较运算符。我认为你误解了变量应该如何嵌入到谓词中。查看Realm模型类定义的摘录,没有名为time的属性,只有dateFrom。类属性应该作为普通字符串位于谓词内部,或者使用%K语法引用,而应该使用%@语法引用要过滤的变量名称。

下面的代码在Realm playground中测试并输出预期结果。

class DeviceDataRealm: Object {
    var uuid: String = ""
    var resolutionID: Int = 0
    var dateFrom: Date = Date()
}

let deviceData = [DeviceDataRealm(value: ["dateFrom":Date.distantPast,"resolutionID":1]),DeviceDataRealm(value: ["dateFrom":Date.distantFuture,"resolutionID":2])]
try! realm.write {
    realm.add(deviceData)
}

let searchUuid = "",searchResolutionID = 2, searchDateFrom = Date()
print(realm.objects(DeviceDataRealm.self).filter("uuid = %@ AND resolutionID = %@ AND dateFrom > %@", searchUuid, searchResolutionID, searchDateFrom))

输出:

  

结果< 0x7fcc2c642280> (       [0] DeviceDataRealm {           uuid =;           resolutionID = 2;           dateFrom = 4001-01-01 00:00:00 +0000;       }   )