Why isn't all of the code in my in my findObjectsInBackgroundWithBlock:^ being executed?

| | August 18, 2015

This is the code I have as part of my ViewDidLoad

I’m trying to do something in the part of the code where i have the NSLogs which aren’t be executed. I haven’t been able to find anyone with the same issue?

Where am I going wrong? Thanks in advance!

PFRelation *relation = [staffMember relationForKey:@"completedTraining"];
PFQuery *query = [relation query];
[query includeKey:@"trainingRecordPointer"];
[query findObjectsInBackgroundWithBlock:^(NSArray *completedTrainingRecords, NSError *error){
    if(!error){
        for (PFObject* completedTrainingRecord in completedTrainingRecords) {
            PFObject * recordWtihTypeAndName = [completedTrainingRecord objectForKey:@"trainingRecordPointer"];
            PFObject *outputObject = [[PFObject alloc]initWithClassName:@"NewTrainingRecord"];
            NSString *recordName = [recordWtihTypeAndName valueForKey:@"RecordName"];
            [completeRecordsWithType addObject:recordName];
            [outputObject addObject:recordName forKey:@"recordName"];
            [outputObject addObject:completedTrainingRecord.createdAt forKey:@"date"];
            [[trainingRecordsDictionary objectForKey:[recordWtihTypeAndName objectForKey:@"Type"]] addObject:outputObject];
            [self.tableView reloadData]; //it works up to this point but if I move this line outside
            //the for-loop nothing happens
            NSLog(@"this will execute"); // does execute

        }
        NSLog(@"this wont execute"); // doesn't execute

    } else {
        NSLog(@"Error: %@ %@", error, [error userInfo]);
    }
    NSLog(@"this wont execute"); // doesn't execute

}];

One Response to “Why isn't all of the code in my in my findObjectsInBackgroundWithBlock:^ being executed?”

  1. You should move [self.tableView reloadData]; to outside your for-loop.

    You should also make sure the tableview is reloaded on the mainthread, and not in this background thread.

    Maybe like this:

    [query findObjectsInBackgroundWithBlock:^(NSArray *completedTrainingRecords, NSError *error){
        if(!error){
            for (PFObject* completedTrainingRecord in completedTrainingRecords) {
    
                     ... do your stuff ...
    
            }
             __weak typeof(self) weakSelf = self;
                dispatch_async(dispatch_get_main_queue(), ^ {
                      [weakSelf.tableView reloadData];
            });
        }
    }];
    

    You probably get into trouble because you try to modify your UI on a backgroundthread.

Leave a Reply