您的位置:首页 > 产品设计 > UI/UE

iOS开发,在main thread以外的thread更新UI

2017-02-22 17:27 423 查看
如果需要在异步任务(Async Task)中更新UI,若直接设置UI,会导致程序崩溃。

例如,在异步block中去更改UI:

NSOperationQueue *queue=[[NSOperationQueue alloc] init];
[queue addOperationWithBlock:^{
@autoreleasepool {
// the other codes ...
_textView.text = [_textView.text stringByAppendingString:stringResult];
}
}];


运行时会崩溃,并报错,意思是此操作只能在主线程执行:

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Only run on the main thread!'


正确的方法是通过mainQueue向主线程队列添加block来执行更新UI,如下:

NSOperationQueue *queue=[[NSOperationQueue alloc] init];
[queue addOperationWithBlock:^{
@autoreleasepool {
// the other codes ...
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
// update UI here
_textView.text = [_textView.text stringByAppendingString:stringResult];
}];
}
}];
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: