gpt4 book ai didi

ios - 如何过滤多个变量,其中之一是 Swift 中的日期?

转载 作者:搜寻专家 更新时间:2023-11-01 07:08:59 24 4
gpt4 key购买 nike

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))

有什么想法吗??

谢谢。

最佳答案

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

但是,问题在于混淆了比较运算符。我认为您误解了变量应该如何嵌入到谓词中。查看 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))

输出:

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

关于ios - 如何过滤多个变量,其中之一是 Swift 中的日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46053132/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com