使用游标

时间:2015-07-05 12:01:40

标签: ios objective-c uicollectionview cloudkit

我有一个应用程序,其中包含从CloudKit中提取的图像集合视图。我有一个CKManager类,它执行所有CK相关的方法。在viewcontroller中,我在CKManager中调用一个方法来从CK中检索初始数据,这些数据都完美无缺。我正在使用CKQueryOperation,所以我可以在块中提取数据,虽然到目前为止我只是为了测试而设置了ckQueryOperation.resultsLimit = CKQueryOperationMaximumResults。因此,在滚动集合视图时,滚动时图像/单元格不会“淡入”。我假设这是因为在渲染单元格之前已经检索了所有数据。目前大约有50条记录并且加载速度相当快,但是当我将结果限制设置为25时,它肯定加载得更快。

我的问题是我不完全理解如何使用游标执行此操作,即使我已经通过在我的代码中实现游标来计划它。我发现这个thread在很大程度上是我理解的,但是它在Swift中并且它也没有回答我的所有问题。我根据Edwin在该主题中的答案修改了我的代码,但我确信我在Swift to OB-C翻译中遗漏了一些内容。

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

非常感谢!

UPDATED:更改了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];
    }

}

从ViewController方法中调用CKManager来获取数据......

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

1 个答案:

答案 0 :(得分:1)

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

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