我有一个具有从CloudKit提取的图像的collectionview的应用程序。我有一个CKManager类,它执行所有与CK相关的方法。在视图控制器中,我在CKManager中调用了一个方法来从CK检索初始数据,这些方法都可以很好地工作。我正在使用CKQueryOperation,所以我可以按块提取数据,尽管到目前为止,我只是为了测试而设置ckQueryOperation.resultsLimit = CKQueryOperationMaximumResults。结果,滚动集合视图时,图像/单元格不会在滚动时“淡入”。我认为这是因为在渲染单元格之前已检索了所有数据。目前大约有50条记录,并且加载速度相当快,但是当我将结果限制设置为25时,加载速度肯定更快。

我的问题是,即使我已经计划在代码中实现一个游标,但我仍不完全了解如何使用游标来执行此操作。我找到了我最了解的thread,但是它在Swift中,并且也不能回答我的所有问题。我根据该线程中Edwin的答案修改了我的代码,但是我确定我在Swift到OB-C的翻译中缺少了一些东西。

下面是我在CKManager类中调用的代码。从日志记录中我可以看到它正在正常工作并可以识别光标。我不明白的是,如何/何时再次调用它以从该光标点获取下一个结果块?如果没有将resultsLimit设置为最初的最大值,我将获得指定的结果量(20),并且不会检索剩余的结果。所以我不知道如何在光标停下的地方得到剩余的结果。我确实知道,因为我使用的是collectionview,所以每次获得下一个结果块时,都需要更新section中的项目数。

首先十分感谢!

更新:更改了loadCloudKitDataWithCompletionHandler,以添加对接受光标的新方法的调用-loadCloudKitDataFromCursor:withCompletionHandler:。唯一缺少的就是找出游标在ViewController中的哪个位置,以使用游标更新numberOfItemsInSection然后重新加载CollectionView来处理方法返回的结果。

从CKManager ...

- (void)loadCloudKitDataFromCursor:(CKQueryCursor *)cursor withCompletionHandler:(void (^)(NSArray *, CKQueryCursor *, NSError *))completionHandler {
    NSMutableArray *cursorResultSet = [[NSMutableArray alloc] init];
    __block NSArray *results;

    if (cursor) { // make sure we have a cursor to continue from
        NSLog(@"INFO: Preparing to load records from cursor...");
        CKQueryOperation *cursorOperation = [[CKQueryOperation alloc] initWithCursor:cursor];
        cursorOperation.resultsLimit = 20;

        // processes for each record returned
        cursorOperation.recordFetchedBlock = ^(CKRecord *record) {
            NSLog(@"RecordFetchBlock returned from cursor CID record: %@", record.recordID.recordName);
            [cursorResultSet addObject:record];
        };
        // query has completed
        cursorOperation.queryCompletionBlock = ^(CKQueryCursor *cursor, NSError *error) {
            results = [cursorResultSet copy];
            [cursorResultSet removeAllObjects]; // get rid of the temp results array
            completionHandler(results, cursor, error);
            if (cursor) {
                NSLog(@"INFO: Calling self to fetch more data from cursor point...");
                [self loadCloudKitDataFromCursor:cursor withCompletionHandler:^(NSArray *results, CKQueryCursor *cursor, NSError *error) {
                    results = [cursorResultSet copy];
                    [cursorResultSet removeAllObjects]; // get rid of the temp results array
                    completionHandler(results, cursor, error);
                }];
            }
        };

        [self.publicDatabase addOperation:cursorOperation];
    }

}

- (void)loadCloudKitDataFromCursor:(CKQueryCursor *)cursor withCompletionHandler:(void (^)(NSArray *, CKQueryCursor *, NSError *))completionHandler {
    NSMutableArray *cursorResultSet = [[NSMutableArray alloc] init];
    __block NSArray *results;

    if (cursor) { // make sure we have a cursor to continue from
        NSLog(@"INFO: Preparing to load records from cursor...");
        CKQueryOperation *cursorOperation = [[CKQueryOperation alloc] initWithCursor:cursor];
        cursorOperation.resultsLimit = 20;

        // processes for each record returned
        cursorOperation.recordFetchedBlock = ^(CKRecord *record) {
            NSLog(@"RecordFetchBlock returned from cursor CID record: %@", record.recordID.recordName);
            [cursorResultSet addObject:record];
        };
        // query has completed
        cursorOperation.queryCompletionBlock = ^(CKQueryCursor *cursor, NSError *error) {
            results = [cursorResultSet copy];
            [cursorResultSet removeAllObjects]; // get rid of the temp results array
            completionHandler(results, cursor, error);
            if (cursor) {
                NSLog(@"INFO: Calling self to fetch more data from cursor point...");
                [self loadCloudKitDataFromCursor:cursor withCompletionHandler:^(NSArray *results, CKQueryCursor *cursor, NSError *error) {
                    results = [cursorResultSet copy];
                    [cursorResultSet removeAllObjects]; // get rid of the temp results array
                    completionHandler(results, cursor, error);
                }];
            }
        };

        [self.publicDatabase addOperation:cursorOperation];
    }

}

从调用CKManager的ViewController方法内部获取数据...
dispatch_async(queue, ^{
        [self.ckManager loadCloudKitDataWithCompletionHandler:^(NSArray *results, CKQueryCursor *cursor, NSError *error) {
            if (!error) {
                if ([results count] > 0) {
                    self.numberOfItemsInSection = [results count];
                    NSLog(@"INFO: Success querying the cloud for %lu results!!!", (unsigned long)[results count]);
                    [self loadRecipeDataFromCloudKit]; // fetch the recipe images from CloudKit
                    // parse the records in the results array
                    for (CKRecord *record in results) {
                        ImageData *imageData = [[ImageData alloc] init];
                        CKAsset *imageAsset = record[IMAGE];
                        imageData.imageURL = imageAsset.fileURL;
                        imageData.imageName = record[IMAGE_NAME];
                        imageData.imageDescription = record[IMAGE_DESCRIPTION];
                        imageData.userID = record[USER_ID];
                        imageData.imageBelongsToCurrentUser = [record[IMAGE_BELONGS_TO_USER] boolValue];
                        imageData.recipe = [record[RECIPE] boolValue];
                        imageData.liked = [record[LIKED] boolValue]; // 0 = No, 1 = Yes
                        imageData.recordID = record.recordID.recordName;
                        // check to see if the recordID of the current CID is userActivityDictionary. If so, it's in the user's private
                        // data so set liked value = YES
                        if ([self.imageLoadManager lookupRecordIDInUserData:imageData.recordID]) {
                            imageData.liked = YES;
                        }
                        // add the CID object to the array
                        [self.imageLoadManager.imageDataArray addObject:imageData];

                        // cache the image with the string representation of the absolute URL as the cache key
                        if (imageData.imageURL) { // make sure there's an image URL to cache
                            if (self.imageCache) {
                                [self.imageCache storeImage:[UIImage imageWithContentsOfFile:imageData.imageURL.path] forKey:imageData.imageURL.absoluteString toDisk:YES];
                            }
                        } else {
                            NSLog(@"WARN: CID imageURL is nil...cannot cache.");
                            dispatch_async(dispatch_get_main_queue(), ^{
                                //[self alertWithTitle:@"Yikes!" andMessage:@"There was an error trying to load the images from the Cloud. Please try again."];
                                UIAlertView *reloadAlert = [[UIAlertView alloc] initWithTitle:YIKES_TITLE message:ERROR_LOADING_CK_DATA_MSG delegate:nil cancelButtonTitle:CANCEL_BUTTON otherButtonTitles:TRY_AGAIN_BUTTON, nil];
                                reloadAlert.delegate = self;
                                [reloadAlert show];
                            });
                        }
                    }
                    // update the UI on the main queue
                    dispatch_async(dispatch_get_main_queue(), ^{
                        // enable buttons once data has loaded...
                        self.userBarButtonItem.enabled = YES;
                        self.cameraBarButton.enabled = YES;
                        self.reloadBarButton.enabled = YES;

                        if (self.userBarButtonSelected) {
                            self.userBarButtonSelected = !self.userBarButtonSelected;
                            [self.userBarButtonItem setImage:[UIImage imageNamed:USER_MALE_25]];
                        }
                        [self updateUI]; // reload the collectionview after getting all the data from CK
                    });
                }
                // load the keys to be used for cache look up
                [self getCIDCacheKeys];
            } else {
                NSLog(@"Error: there was an error fetching cloud data... %@", error.localizedDescription);
                dispatch_async(dispatch_get_main_queue(), ^{
                    //[self alertWithTitle:@"Yikes!" andMessage:@"There was an error trying to load the images from the Cloud. Please try again."];
                    UIAlertView *reloadAlert = [[UIAlertView alloc] initWithTitle:YIKES_TITLE message:ERROR_LOADING_CK_DATA_MSG delegate:nil cancelButtonTitle:CANCEL_BUTTON otherButtonTitles:TRY_AGAIN_BUTTON, nil];
                    reloadAlert.delegate = self;
                    [reloadAlert show];
                });
            }
        }];
    }

最佳答案

你近了对于newOperation,您还必须设置recordFetchedBlock和queryCompletionBlock。当您将新操作分配给该操作并执行该操作时,您将不会丢失引用,并且代码将继续运行。
替换一行[self.publicDatabase addOperation:newOperation];与:

newOperation.recordFetchedBlock = operation.recordFetchedBlock
newOperation.queryCompletionBlock = operation.queryCompletionBlock
operation = newOperation
[self.publicDatabase addOperation:operation];

08-15 20:51