2015-08-13 242 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沒有被執行..謝謝你的例子。很高興知道。 –

相關問題