This application is modifying the autolayout engine from a background thread

来源:互联网 发布:成都php 编辑:程序博客网 时间:2024/05/22 07:02

我在用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];



0 0
原创粉丝点击