我正在从我的数据库中检索数据,并使用结构来处理该对象。我需要访问下面的newObj
,但图片为nil
。当我在从数据到UIImage
的转换中打印图像时,图像存在,但是当我在.getDataInBackground
下打印它时,它是零。我猜我必须将它放在块中或在同步线程上运行它?处理这个问题的正确方法是什么?
var pic = UIImage()
pic.getDataInBackground(block: { (data: Data?, error: Error?) in
if(error == nil){
let newPic = UIImage(data: data!)
if(newPic != nil){
pic = newPic!
print("inside block \(pic)") //returns data
}
}else{
print(error)
}
})
print(pic) // returns 0
let newObj = Obj(name: "Bob", pic: pic)
答案 0 :(得分:1)
getDataInBackground
闭包正在后台线程上运行,并且需要一些时间,代码在关闭之后执行,之后调用闭包,因此pic没有&#t; t有机会初始化。
在您当前的代码中,print语句的顺序应为:
UIImage() // via `print(pic)`
inside block UIImage() // via `print("inside block \(pic)")`
您可能希望在闭包范围内创建newObj
,如下所示:
pic.getDataInBackground(block: { (data: Data?, error: Error?) in
// #3 0.25s
if(error == nil){
let newPic = UIImage(data: data!)
if(newPic != nil){
pic = newPic!
print("inside block \(pic)")
let newObj = Obj(name: "Bob", pic: pic)
// pass the new object back to the main queue through
// a method
DispatchQueue.main.async {
collectObj(newObj)
}
}
}
else{
print(error)
}
})