Search code examples
objective-ccloudkit

CloudKit Query Time


I've just started trialling CloudKit and am having some pretty slow query times. Here is some sample code I am using:

//CLOUDKIT
    CKContainer *container = [CKContainer defaultContainer];
    CKDatabase *privateDatabase = [container privateCloudDatabase];
    
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"TRUEPREDICATE"];
    CKQuery *query = [[CKQuery alloc] initWithRecordType:@"FlightLog" predicate:predicate];
    
    [privateDatabase performQuery:query inZoneWithID:nil completionHandler:^(NSArray *results, NSError *error) {
        //SUCCESS
        if (!error)
        {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"SUCCESS" message:@"IT WORKED" delegate:self cancelButtonTitle:@"dismiss" otherButtonTitles:nil];
            [alert show];

            NSLog(@"%@", @"fetchFlights success!");
            NSLog(@"%@", self.fetchedRecords);

            self.fetchedRecords = results;
            [self.tableView reloadData];
        }
        //ERROR
        else
        {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"error" message:error.localizedDescription delegate:self cancelButtonTitle:@"dismiss" otherButtonTitles:nil];
            [alert show];

            NSLog(@"%@", error);
        }
        
    }];

I get the private database, and query for all records. There is just four simple ones I added in the dashboard.

Upon calling this code, I can see from my console log that the success message gets called almost immediately, with a null results array. Then moments later, the results are returned, as seen in the log. However, the alert view isn't shown and results displayed in my table for about 3-4 more seconds.

What's going on?


Solution

  • This is resolved. As Edwin mentions, I didn't know that the callback is on a background thread. So when I call [self.tableView reloadData] in the completion block, it is also running on the background thread.

    By putting it back on the main thread, the table view reloads within about a second. Vs taking about 4-5 seconds if running on the same thread as the callback.

        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
            dispatch_async(dispatch_get_main_queue(), ^{
                               [self.tableView reloadData];
                           });
        });
    

    Let me know if I have misunderstood, but I think that's what has happened.