2017-09-05 45 views
0

境界版本 - > 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)) 

任何想法??

謝謝。

+0

您是否真的在尋找過去或未來的日期?我認爲這只是你的比較運算符翻轉。 –

回答

1

使用謂詞時,不應將變量值嵌入到謂詞中,因爲這通常會導致問題,但應該在謂詞中使用%@並在謂詞後面寫入變量名稱。

但是,問題在於混合了比較運算符。我想你錯誤地理解了變量應該如何嵌入到謂詞中。查看Realm模型類定義的摘錄,沒有名爲time的屬性,只有dateFrom。類屬性應該在謂詞中作爲普通字符串使用,或者使用%K語法引用,而您要過濾的變量名稱應該使用%@語法引用。

下面的代碼在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)) 

輸出:

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

相關問題