2015-01-09 68 views
1

我有一個表格視圖和一個自定義的單元格被加載和設置,但問題是數據不加載,除非我旋轉設備。在縱向模式下,當我第一次運行它時,沒有任何東西存在,一旦我旋轉設備,所有數據加載並完美工作。有什麼建議麼?iOS的表格視圖只加載設備旋轉的數據

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
    static NSString *CellIdentifier = @"CellIdentifier"; 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
    if (cell == nil) { 
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; 
    } 
    cell.textLabel.text = @"Hello"; return cell; 
} 

數據加載 -

PFQuery *query = [PFQuery queryWithClassName:@"Post"]; 
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) { 
    if (!error) { 
     NSLog(@"%@", objects); 
     _postsArray = [[NSArray alloc] initWithArray:objects]; 
    } else { 
     UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"There was an error loading the posts. Please try again" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil]; 
     [alert show]; 
    } 
}]; 
[self.tableView reloadData]; 

回答

2

你的問題是,你是異步加載數據,一旦裝載完成時不調用reloadData。你確實調用這個方法,但是在塊之外,所以它會在加載完成之前立即執行。

你的數據加載方法應該是 -

PFQuery *query = [PFQuery queryWithClassName:@"Post"]; 
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) { 
    if (!error) { 
     NSLog(@"%@", objects); 
     _postsArray = [[NSArray alloc] initWithArray:objects]; 
     dispatch_async(dispatch_get_main_queue(),^{ 
      [self.tableView reloadData]; 
     }); 
    } else { 
     UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"There was an error loading the posts. Please try again" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil]; 
     dispatch_async(dispatch_get_main_queue(),^{ 
      [alert show]; 
     }); 
    } 
}]; 

注意影響UI操作都需要在主隊列中進行。