[英]How can I filter multiple variables and one of them is a Date in Swift?
Realm version -> 2.10 领域版本-> 2.10
Swift version > 3 迅捷版> 3
var uuid: String
var resolutionID: Int
var dateFrom: Date
...
I checked that the variables are not null. 我检查了变量是否不为空。 I tried:
我试过了:
realm.objects(DeviceDataRealm.self).filter("device.uuid == '\(uuid)' AND resolution.idResolution == \(resolutionID) AND time > \(dateFrom)")
It does not work... 这是行不通的...
I tried with NSPredicate
too: 我也尝试过
NSPredicate
:
let predicate = NSPredicate(format: "device.uuid = %@ AND resolution.idResolution = %@ AND time > %@", uuid, resolutionID, dateFrom as CVarArg)
realm.objects(DeviceDataRealm.self).filter(predicate)
It works only without the Date
variable: 它仅在没有
Date
变量的情况下有效:
realm.objects(DeviceDataRealm.self).filter("device.uuid == '\(uuid)' AND resolution.idResolution == \(resolutionID))
Any idea?? 任何想法??
Thanks. 谢谢。
When using predicates, you shouldn't embed the variable values inside the predicates, since that can often lead to problems, but should use the %@
inside the predicate and write the variable names after the predicate. 使用谓词时,不应将变量值嵌入谓词中,因为这通常会导致问题,而应在谓词中使用
%@
并在谓词后写入变量名称。
However,the issue was with mixing up the comparison operators. 但是,问题在于混淆比较运算符。 I think you misunderstood how variables should be embedded to predicates.
我认为您误解了如何将变量嵌入谓词。 Looking at the extract of your Realm model class definition, there's no property named
time
, only dateFrom
. 查看Realm模型类定义的摘录,没有名为
time
的属性,只有dateFrom
。 Class properties should either be inside the predicate as normal Strings or referred to using the %K
syntax, while the variable names you want to filter for should be referenced to using the %@
syntax. 类属性应在谓词中作为普通字符串包含在内部,或使用
%K
语法进行引用,而要过滤的变量名应使用%@
语法进行引用。
Below code was tested in a Realm playground and outputs the expected result. 下面的代码在Realm游乐场中经过测试,并输出预期结果。
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))
Output: 输出:
Results <0x7fcc2c642280> ( [0] DeviceDataRealm { uuid = ; resolutionID = 2; dateFrom = 4001-01-01 00:00:00 +0000; } )
结果<0x7fcc2c642280>([0] DeviceDataRealm {uuid =; resolutionID = 2; dateFrom = 4001-01-01 00:00:00 +0000;})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.