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.

Xcode7.2报错:
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.
Apple推荐在主线程内更新UI,非子线程内更新UI会报该错误.
解决方法:
子线程内执行Image下载,再传递到主线程更新UI
Demo_1:(NSThread方式):

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    
    [self performSelectorInBackground:@selector(downloadImage) withObject:nil];
}

-(void)downloadImage
{
    @autoreleasepool {
#warning NSThread 方法注意:子线程的runloop默认不开启,子线程里使用的类方法都是autorease的话,就会没有autoreleasepool可放,也就意味着后面没有方法就行释放,造成内存泄露.
        
        NSLog(@"thread = %@",[NSThread currentThread]);
        
        //    1.url
        NSURL *url = [NSURL URLWithString:@"http://e.hiphotos.baidu.com/image/pic/item/29381f30e924b8995d7368d66a061d950b7bf695.jpg"];
        
        //    2.download
        NSData *data =[NSData dataWithContentsOfURL:url];
        
        //    3.二进制文件转图片
        UIImage *image = [UIImage imageWithData:data];
        
        //    4.显示
#warning 不要在子线程更新UI self.imgView.image = image;
        //    方法1
        [self performSelectorOnMainThread:@selector(downloadDidFinish:) withObject:image waitUntilDone:NO];
        //    方法2
        [self performSelector:@selector(downloadDidFinish:) onThread:[NSThread mainThread] withObject:image waitUntilDone:NO];
        //    直接调用setImage:即可
        //    [self.imgView performSelectorOnMainThread:@selector(setImage:) withObject:image waitUntilDone:NO];
    }
}

-(void)downloadDidFinish:(UIImage *)image
{
    NSLog(@"thread = %@",[NSThread currentThread]);
    self.imgView.image = image;
}

Demo_2:(GCD方式)

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSLog(@"thread = %@",[NSThread currentThread]);
        
        //    1.url
        NSURL *url = [NSURL URLWithString:@"http://e.hiphotos.baidu.com/image/pic/item/29381f30e924b8995d7368d66a061d950b7bf695.jpg"];
        
        //    2.download
        NSData *data =[NSData dataWithContentsOfURL:url];
        
        //    3.二进制文件转图片
        UIImage *image = [UIImage imageWithData:data];
        //    4.主线程赋值
        dispatch_async(dispatch_get_main_queue(), ^{
            self.imgView.image = image;
        });
    });
}

Stack overflow相关问题:http://stackoverflow.com/questions/32680303/ios9-this-application-is-modifying-the-autolayout-engine-from-a-background-thr

你可能感兴趣的:(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.)