为什么我的findObjectsInBackgroundWithBlock中的所有代码都没有被执行?

时间:2015-08-13 19:52:47

标签: ios objective-c parse-platform

这是我在ViewDidLoad

中的代码

我正在尝试在代码中执行某些操作,其中包含不执行的NSLog。我找不到有同样问题的人?

我哪里错了?提前谢谢!

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

}];

1 个答案:

答案 0 :(得分:1)

您应该将[self.tableView reloadData];移到for循环之外。

您还应确保在mainthread上重新加载tableview,而不是在此后台线程中。

也许是这样的:

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

您可能会遇到麻烦,因为您尝试在后台线程上修改UI。