【问题标题】:How to reload tableView after async fetching JSON ? Objective C异步获取 JSON 后如何重新加载 tableView?目标 C
【发布时间】:2014-06-12 16:32:16
【问题描述】:

这是我异步获取 JSON 的代码

-(void)viewDidAppear:(BOOL)animated
{
 [_indicator startAnimating];
_indicator.hidesWhenStopped = YES;
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
    //Load the json on another thread

    [Constants shared].jsonData = [[NSData alloc] initWithContentsOfURL:
                                   [NSURL URLWithString:@"http://api.fessor.da.kristoffer.office/homework/index/?rp[token]=app&rp[workspace]=parent&child_id=22066&type=parent&start_date=2014-05-01&end_date=2014-05-01"]];

    //When json is loaded stop the indicator
    [_indicator performSelectorOnMainThread:@selector(stopAnimating) withObject:nil waitUntilDone:YES];

    [self declareVariables];
    [_tableView reloadData];

});
}

由于某种原因它无法正常工作。 它显示微调器,我可以看到数据被提取,它停止并隐藏微调器,但 tableView 没有重新加载,它是空白的。

【问题讨论】:

  • _tableView 为零吗?尝试在主线程上调用reloadData
  • 我认为您的问题是在不是主线程的线程上重新加载表。我不会使用 dispatch_async 和 initWithContentsOfURL 来完成这项工作,而是使用 NSURLConnection 的 sendAsynchronousRequest:queue:completionHandler: 它为您提供了一个在主线程上运行的完成块。
  • viewDidAppear 中这样做可能是个坏主意。您确定要在每次可见时刷新此视图吗?此外,“加载”代码并不真正属于视图控制器。

标签: ios objective-c json uitableview


【解决方案1】:

您想将所有 UI 内容移至主队列。所以你的代码应该写成:

-(void)viewDidAppear:(BOOL)animated
{
    [_indicator startAnimating];
    _indicator.hidesWhenStopped = YES;
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(queue, ^{
    //Load the json on another thread

    [Constants shared].jsonData = [[NSData alloc] initWithContentsOfURL:
                                   [NSURL URLWithString:@"http://api.fessor.da.kristoffer.office/homework/index/?rp[token]=app&rp[workspace]=parent&child_id=22066&type=parent&start_date=2014-05-01&end_date=2014-05-01"]];
    dispatch_async(dispatch_get_main_queue(), ^{
       //When json is loaded stop the indicator
       [_indicator stopAnimating];
       [self declareVariables];
       [_tableView reloadData];
       });
    });
}

这样,您的 JSON 会加载到后台队列中,而 UI 会在主队列中更新。

【讨论】:

    【解决方案2】:

    您应该尝试在主线程上重新加载表格视图。使用 GCD 在主线程上调度。

    dispatch_async(dispatch_get_main_queue(), ^{
        [_tableView reloadData];
    });
    

    如果没有结果,尝试登录cellForRowAtIndexPath方法检查是否重新加载完成。如果是这样,你的错误在别处。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-04-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-31
      • 1970-01-01
      相关资源
      最近更新 更多