我对闭包的了解还为时过早,我遇到了从dispatch_async调用中向NSMutableArray添加对象的问题,该调用从web中检索json数据,我试图将对象添加到NSMutableArray,该NSMutableArray在函数外部初始化但仍然存在当我在函数内添加对象时,我确定还有另一种方法.....请帮助!顺便说一句,如果我删除dispatch_async然后一切正常,但我想在另一个线程上进行网络调用。
class Users:NSObject {
var returnedUsersDetailsFromWeb = NSMutableArray()
func detailsOfUsersFromWeb(){
let url = NSURL(string: "http://Sheldons-MacBook-Pro.local/real/get_data.php")
dispatch_async(dispatch_get_global_queue(Int(QOS_CLASS_USER_INITIATED.value), 0)) { () -> Void in
if let data = NSData(contentsOfURL: url!){
var error:NSError?
let arr = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: &error) as! NSArray
for var i = 0 ; i < (arr as NSArray).count ; i++ {
self.returnedUsersDetailsFromWeb.addObject((arr as NSArray) .objectAtIndex(i))
}
}
}
println(self.returnedUsersDetailsFromWeb) // this is empty, if i remove the dispatch_async then this prints out everything
}
}