iOS表视图仅加载设备轮换时的数据

时间:2015-01-09 22:34:45

标签: ios uitableview

我有一个表格视图和一个自定义单元格,它们已加载并设置但问题是除非我旋转设备,否则数据不会被加载。在纵向模式下,当我第一次运行它时,没有任何东西,一旦我旋转设备,所有数据加载和完美工作。有什么建议吗?

- (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];

1 个答案:

答案 0 :(得分: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的操作。