2015-08-13 244 views
1

这是我的代码作为我的ViewDidLoad的一部分为什么我的findObjectsInBackgroundWithBlock:^中没有执行所有的代码?

我想在代码的一部分,我有NSLogs是不会执行的东西。我一直没能找到有同样问题的人?

我哪里错了?提前致谢!

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

您应该将[self.tableView reloadData];移动到您的for-loop外部。

你还应该确保tableview被重新加载到mainthread上,而不是在这个后台线程中。

也许是这样的:

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

你可能遇到麻烦,因为你试图修改一个backgroundthread你的UI。

+0

它需要在后台线程完成,因为我从解析得到的数据是我用来填充tableview。如果我在主线程上做到这一点,就没有任何意义。我会在循环外执行,但循环外没有任何执行。这是我的probelem ... –

+0

是的,你可以从这个后台线程的Parse获取,但是如果你想更新你的UI,你需要在mainthread上做这件事。我更新了我的anser给你一个例子如何做到这一点。 – knutigro

+0

即使我注释掉[tableView reloadData] NSLogs没有被执行..谢谢你的例子。很高兴知道。 –

相关问题