3

我需要获取 cloudkit 中的最后一条记录。这是我的代码:

 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];

我的问题是如何修改我的代码以获取 cloudkit 中的最后一条记录?

我会非常感谢你的帮助

4

3 回答 3

4

您可以对创建数据进行升序排序,然后只要求 1 个这样的结果(代码在 Swift 中):

添加排序:

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

限制结果:

queryOp.resultsLimit = 1
于 2014-12-01T20:05:07.643 回答
1

Objective-C 版本

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

一条记录:

queryOp.resultsLimit = 1;
于 2014-12-01T23:00:54.977 回答
0

设置 resultsLimit 似乎对我不起作用,但是无论如何设置它并使用时间戳或记录创建日期对结果进行排序。然后将结果存储在一个数组中,并根据排序顺序简单地使用第一项或最后一项

    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];
于 2016-11-22T00:58:30.860 回答