若是須要在異步任務(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]; }]; } }];