天天看點

This application is modifying the autolayout engine from a background thread

我在用NSURLSession做請求:

NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://XXX"]]; NSURLRequest *request =[NSURLRequest requestWithURL:url]; NSURLSession *session = [NSURLSession sharedSession]; NSURLSessionDataTask *sessionDataTask = [session dataTaskWithRequest:request     completionHandler:^(NSData *_Nullable data,      NSURLResponse *_Nullable response,       NSError *_Nullable error) {

NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableLeaves) error:nil];

[self.tableView reloadData];

}];

[sessionDataTask resume];

報錯如下:

This application is modifying the autolayout engine from a background thread, which can lead to engine corruption and weird crashes. This will cause an exception in a future release. Stack:(......)

結論:

1、在子線程中是不能進行UI 更新的,而可以更新的結果隻是一個幻像:因為子線程代碼執行完畢了,又自動進入到了主線程,執行了子線程中的UI更新的函數棧,這中間的時間非常的短,就讓大家誤以為分線程可以更新UI。如果子線程一直在運作,則子線程中的UI更新的函數棧 主線程無法獲知,即無法更新

2、隻有極少數的UI能,因為開辟線程時會擷取目前環境,如點選某個按鈕,這個按鈕響應的方法是開辟一個子線程,在子線程中對該按鈕進行UI 更新是能及時的,如換标題,換背景圖,但這沒有任何意義

将上述方法改為:

NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@

"http://XXX"

]];

NSURLRequest *request =[NSURLRequest requestWithURL:url]; NSURLSession *session = [NSURLSession sharedSession]; NSURLSessionDataTask *sessionDataTask = [session dataTaskWithRequest:request  completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {

NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableLeaves) error:nil];

dispatch_async(dispatch_get_main_queue(), ^{

[myTableView reloadData];

});

}];

[sessionDataTask resume];