Kjell Connelly
Kjell Connelly

Reputation: 257

NSPredicate by creationDate, only get first result

I am trying to figure out a way to use a NSPredicate (I think this is the tool I need to use) to use CloudKit to query for the most recent CKRecord of a certain record type.

Because it is only the most recent one, I don't need all of the CKRecords returned to me, nor do I want to set a limited span of time (as this app may have a bunch of people using it at times, and probably will eventually have close to zero people using it). The closest post I could find towards my question involved getting CKRecords between two dates (a few minutes ago, and when the Query was started).

This way, if a person were to get the most recent record and it was 2 months old, or it was 2 seconds old, this query would work.

Anyone know how to do this? I've got the code working for using a predicate that finds all records, so just this part needs fixing. Here's a partial code of the segment I am working on now:

NSPredicate *thePredicate = [NSPredicate predicateWithFormat:@"TRUEPREDICATE"];
CKQuery *query = [[CKQuery alloc] initWithRecordType:@"Photo" predicate:thePredicate];

[[[CKContainer defaultContainer] publicCloudDatabase] performQuery:query inZoneWithID:nil  completionHandler:^(NSArray *results, NSError *error) {

}];

Upvotes: 0

Views: 231

Answers (1)

Edwin Vermeer
Edwin Vermeer

Reputation: 13127

You could solve this by using a CKQueryOperation where you set the resultsLimit to 1. for the query you can just use the truepredicate. on the query add a NSSortDiscriptor for key creationDate and ascending false to the sortDescriptors array. This way the result will always be just 1 record that was inserted most recently. Even if this record was older than the 2 months.

Upvotes: 1

Related Questions