ios - 从 Afnetwork block 更新 ios ui 元素时出现延迟

标签 ios block afnetworking

在我的应用程序中,当用户按下按钮时,我会启动一个 HTTP 异步请求(使用 AFURLConnectionOperation)并更改 completionHandler block 中 UILabel 的文本。但是,此更改不会在请求结束时发生,而是在大约 2-3 秒后发生。下面是导致此行为的代码片段。

    AFURLConnectionOperation* operation = ...
    [opration setCompletionBlock:^{
         NSLog(@"This text appears immediatly");
         [myLabel setText:@"this one is delayed for 2-3 sec"];
    }];
    [opreation start];

寻求帮助

最佳答案

这是尝试从后台队列执行 UI 更新的症状。如果将该 UI 更新添加回主队列,您的问题将得到解决:

[operation setCompletionBlock:^{
     NSLog(@"This text appears immediately");
     [[NSOperationQueue mainQueue] addOperationWithBlock:^{
         [myLabel setText:@"this should not be delayed for 2-3 sec"];
     }];
}];

作为NSOperation documentation对于 setCompletionBlock 来说,您无法保证完成操作将发生在哪个线程上:

The exact execution context for your completion block is not guaranteed but is typically a secondary thread. Therefore, you should not use this block to do any work that requires a very specific execution context. Instead, you should shunt that work to your application’s main thread or to the specific thread that is capable of doing it. ...

UI 更新必须在主队列中进行,因此如果您的完成 block 想要执行 UI 更新,它必须显式地将它们添加到主队列中。

关于ios - 从 Afnetwork block 更新 ios ui 元素时出现延迟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18705684/

相关文章:

magento - Magento 类(class)的长度有限制吗?

C#表达式,相当于ruby的三明治 block 代码

linux - 在没有 fflush(stdout) 的情况下将 block 缓冲数据写入文件

objective-c - 使用 afnetworking 下载文件之前获取文件大小

json - 如何从 JSON 二维结构(嵌套字典)获取值?

ios - 如何设置表格 View 单元格占据整个屏幕?

objective-c - 在后台服务中执行操作的任务

iOS swift Xcode 6 : CGAffineTransformRotate with auto-layout anchorpoint

ios - iOS-使用AFNetworking保存和持久保存JSON结果的策略

jquery - 移动设备上的 ScrollTop