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

若是须要在异步任务(Async Task)中更新UI,若直接设置UI,会致使程序崩溃。app

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

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

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

 *** 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];
        }];
    }
}];
相关文章
相关标签/搜索