8.NSData加載圖片數(shù)據(jù)遇到的一個問題


問題描述:
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)
    }

因為執(zhí)行

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

會阻塞主進程,因此我們需要自行異步調(diào)用此方法來解決問題


改成下面的樣子后就好了

因為是一組圖片,所以我們增加一個異步加載隊列組來管理加載
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

最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內(nèi)容