简体   繁体   中英

Using “timeIntervalSinceNow” in a predicate in SWIFT

I am trying to query for records that are created in the last 1 hour using Cloudkit (in SWIFT)

I have tried:

let predicate = NSPredicate(predicateWithFormat : "timeIntervalSinceNow %@ < %f", "creationTime", -3600)

without success. The error message refers to a parsing error.

Anyone has a clue what would be the right format?

nb creationTime is the name of the field in the Table

Your predicate isn't valid. Take a look at Apple's guide for creating NSPredicates .

You should use a key path on the left hand side of the expression. I assume that you have an array of objects, and these objects have a property named creationTime . Then the predicate should look like this:

NSPredicate(format: "creationTime.timeIntervalSinceNow > %d", -3600)

Note that I have used "greater than" > operator instead of < in the predicate you posted. That's because a date from the past will return a negative value from timeIntervalSinceNow method, as documentation states.

EDIT: Seems you can't use key paths in CloudKit predicates. But I think you can create a reference date (an hour ago) and use it for comparison predicate:

let now = NSDate()
if let anHourAgo = NSCalendar.currentCalendar().dateByAddingUnit(
    .HourCalendarUnit,
    value: -1,
    toDate: now,
    options: NSCalendarOptions(0)) {
        let predicate = NSPredicate(format: "creationDate > %@", anHourAgo)
        let filtered = records.filteredArrayUsingPredicate(predicate!)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM