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