8.NSData加载图片数据遇到的一个问题


问题描述:
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.


问题代码 :

func loadImage(imageURL:String){
        print("image url->",imageURL)
        let url = NSURL(string: imageURL)
        let data = try? NSData(contentsOfURL: url!, options: NSDataReadingOptions.DataReadingMappedIfSafe)
        let image = UIImage(data: data!)
        self.images.append(image)
    }

因为执行

NSData(contentsOfURL: url!, options: NSDataReadingOptions.DataReadingMappedIfSafe)

会阻塞主进程,因此我们需要自行异步调用此方法来解决问题


改成下面的样子后就好了

因为是一组图片,所以我们增加一个异步加载队列组来管理加载
func loadImages(images:[String]) {
        let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
        let queueGroup = dispatch_group_create()
        dispatch_group_async(queueGroup, queue, {
            for imageURL in images{
                self.loadImage(imageURL)
            }
        })
        dispatch_group_notify(queueGroup, dispatch_get_main_queue(), {
            //将加载完成后的图片添加到视图
            self.addImages()
        })
    }
func loadImage(imageURL:String){
        print("image url->",imageURL)
        let url = NSURL(string: imageURL)
        let data = try? NSData(contentsOfURL: url!, options: NSDataReadingOptions.DataReadingMappedIfSafe)
        let image = UIImage(data: data!)
        self.images.append(image!)
    }

更具体的线程讲解可以参考这篇文章或者自行搜索
http://blog.csdn.net/totogo2010/article/details/8016129

你可能感兴趣的:(8.NSData加载图片数据遇到的一个问题)