Loading

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

如果需要在异步任务(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];
        }];
    }
}];

 

posted @ 2017-02-22 17:27  gamesun  阅读(803)  评论(0编辑  收藏  举报