【问题标题】:sendAsynchronousRequest with tableView reloadData delay on draw绘制时带有 tableView reloadData 延迟的 sendAsynchronousRequest
【发布时间】:2011-11-17 15:30:20
【问题描述】:

我正在尝试使用 iOS5 中添加的新 sendAsynchronousRequest。 我有一个模型类(File),它的方法从服务器请求一些数据,然后将这些数据传递给创建模型对象的控制器类(FilesController)。

模型类有一个方法,代码如下:

[NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
    NSArray *decodedResponse = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    NSArray *files = [self _dictionariesToFiles:decodedResponse];
    handler(files);
}];

控制器类,像这样使用它:

[File findAll:conditions completionHandler:^(NSArray *files) {
    dataSource = files;

    NSLog(@"set");

    [self.tableView reloadData];

    NSLog(@"reload");

    activityIndicator.hidden = TRUE;
}];

在控制台中,我可以立即查看 NSLogs 如何显示“设置”和“重新加载”消息,但表格和指示器直到几秒钟(5-10 秒)过去后才会改变。

有人知道问题出在哪里吗?

谢谢。

PD:我用兼容的同步请求更改了异步请求,然后问题消失了,但我想为此使用异步请求。

这是兼容的同步码:

NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSArray *decodedResponse = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:nil];
NSArray *files = [self _dictionariesToFiles:decodedResponse];
handler(files);

【问题讨论】:

    标签: objective-c ios xcode ios5


    【解决方案1】:

    你需要在主线程上做[tableView reloadData]。所有 UI 操作都必须在主线程上完成。有多种方法可以做到这一点。一种是:

    dispatch_async(dispatch_get_main_queue(), ^{
        [self.tableView reloadData];
        activityIndicator.hidden = TRUE;
    });
    

    编辑:将 activityIndi​​cator 添加到示例

    【讨论】:

      【解决方案2】:

      我在使用[[NSOperationQueue alloc] init] 时确实遇到了一些问题,但使用[NSOperationQueue mainQueue] 一切都很完美。使用新的 Queue 执行行不遵循自然顺序

      【讨论】:

      • 那是因为 mainQueue 在主线程上运行,这是所有 UI 工作都必须发生的地方。
      • @Rscorreia greenisus 是正确的,在我发现这个之前,我遇到了和你一样的问题。
      • @greenisus 那么如何让异步请求快速工作呢?如果你这样做[NSOperationQueue mainQueue],它将把它放在主线程上,这首先破坏了使用异步请求的目的......?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-12-14
      • 1970-01-01
      • 2017-07-26
      • 1970-01-01
      • 1970-01-01
      • 2011-04-06
      • 2011-09-17
      相关资源
      最近更新 更多