CKQueryOperation gets the last record

I need to get the most recent cloudkit entry. 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 change my code to get the most recent entry in cloudkit?

I will be very grateful for your help.

+3


source to share


3 answers


You can sort by creation in ascending order and then just request 1 result like this (the code is in Swift):

Adding sorting:

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

      



Limiting the result:

queryOp.resultsLimit = 1

      

+4


source


Objective-C version

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

      



for one entry:

queryOp.resultsLimit = 1;

      

+1


source


Setting the results Limit didn't seem to work for me, but set it up anyway and sorted the results using the timestamp or date the entry was created. Then store the results in an array and just use the first or last element 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];

      

0


source







All Articles