CKQueryOperation get the last record

1.3k views Asked by At

I need to fetch the very last record in cloudkit. Here is my code:

 CKContainer *container = [CKContainer containerWithIdentifier:containerID];
    CKDatabase *publicDatabase = [container publicCloudDatabase];
    CKQuery *query = [[CKQuery alloc] initWithRecordType:recordType
                                               predicate:[NSPredicate predicateWithFormat:@"TRUEPREDICATE"]];
     CKQueryOperation *queryOp = [[CKQueryOperation alloc] initWithQuery:query];

    queryOp.desiredKeys = @[@"record.recordID.recordName"];
    queryOp.recordFetchedBlock = ^(CKRecord *record)
    {
        //do something
    };

     queryOp.queryCompletionBlock = ^(CKQueryCursor *cursor, NSError *error)
    {
        NSLog(@"CKQueryCursor  error %@", error);
    };

    queryOp.resultsLimit = CKQueryOperationMaximumResults;
    [publicDatabase addOperation:queryOp];

My question is how can I modify my code to get the very last record in cloudkit?

I'll really appreciate your help

3

There are 3 answers

0
user2924482 On

Objective-C version

    NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:NO];
query.sortDescriptors = @[sortDescriptor];

for one record:

queryOp.resultsLimit = 1;
1
Edwin Vermeer On

You can sort on the creation dat ascending and then just ask for 1 result like this (code is in Swift):

Adding the sort:

query.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]

Limiting the result:

queryOp.resultsLimit = 1
0
Duncan Groenewald On

Setting resultsLimit does not seem to work for me, however set it anyway and sorting the results using a timestamp or the record creation date. Then store the results in an array and simply use the first or last item depending on the sort order

    CKContainer *container = [CKContainer containerWithIdentifier:containerID];
    CKDatabase *publicDatabase = [container publicCloudDatabase];
    CKQuery *query = [[CKQuery alloc] initWithRecordType:recordType predicate:[NSPredicate predicateWithFormat:@"TRUEPREDICATE"]];

    NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:NO];
    query.sortDescriptors = @[sortDescriptor];

    CKQueryOperation *queryOp = [[CKQueryOperation alloc] initWithQuery:query];
    queryOp.desiredKeys = @[@"record.recordID.recordName"];
    queryOp.recordFetchedBlock = ^(CKRecord *record)
    {
        //do something
        recordArray.append(record)
    };

    queryOp.queryCompletionBlock = ^(CKQueryCursor *cursor, NSError *error)
    {
        NSLog(@"CKQueryCursor  error %@", error);
        let myLastRecord = recordArray[recordArray.count - 1]
    };

    queryOp.resultsLimit = CKQueryOperationMaximumResults;
    [publicDatabase addOperation:queryOp];