I'm new to CloudKit (and haven't used NSPredicate much) and am looking to do something which, I'd imagine, is quite basic. I'd like to retrieve the data record with the newest creationDate.
Right now I'm just pulling all the records and scooping up the last one, but there's got to be a more elegant way. Here's my current approach:
let predicate = NSPredicate(value: true)
let query = CKQuery(recordType: "NewsItem", predicate: predicate)
CKContainer(identifier: "…").publicCloudDatabase.perform(query, inZoneWith: CKRecordZone.default().zoneID) { result, error in
let sortedRecords = result.sorted {
guard let date1 = $0.value(forKey: "creationDate") as? Date,
let date2 = $1.value(forKey: "creationDate") as? Date else {
return false
}
return date1 < date2
}
let item = NewsItem(from: sortedRecords[0])
…
}
I've used NSPredicate to get a subset of results before, but never max/min style results. Is this possible?
This seems like a step in the right direction:
Though I'm still curious if there's a way to simply query by max creationDate…