更新UI是必须回到主线程的,如果你是在网络请求的子线程中做操作,然后想更新UI的操作,那么需要把更新操作加入主队列,主队列的任务都是在主线程中执行的,这时需要用到GCD技术。
一般只需要这样写就可以
dispatch_async(dispatch_get_global_queue(disPATCH_QUEUE_PRIORITY_DEFAULT,0),{
//需要长时间处理的代码
dispatch_async(dispatch_get_main_queue(),{
//需要主线程执行的代码
})
})参考:
http://www.starming.com/index.php?v=index&view=24
其实只要用这个异步回调主线程就可以:
dispatch_async(dispatch_get_main_queue(),{
//dosomething
self
.
orgnameLabel
.
text
=
"
测试
"
})
如果不这样会报异常: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.
并且更新UI不成功。
完整例子:
@IBAction func click(sender: AnyObject) {
self.imageView.image = nil
let imgkURL = NSURL(string : STR_URL)
let priority = disPATCH_QUEUE_PRIORITY_DEFAULT
dispatch_async(dispatch_get_global_queue(priority,{
let imgData = NSData(contentsOfURL : imgkURL!)
let img = UIImage(data : imgData!)
dispatch_async(dispatch_get_main_queue(),{
self.imageView.image = img
})
})
}