从解析查询块返回 UIImage 数组 [英] Return UIImage Array From Parse Query Block
问题描述
我无法从该函数中获得 [UIImage?] 返回值.getDataInBackgroundWithBlock
不会让我设置除 Void in
以外的返回值.但是,该块会在迭代时添加到 iconArray
中.但是一旦在块之外,数组又是空的.您将在下面的代码中看到数组正确打印和未正确打印的注释.
I cannot get a [UIImage?] return from this function. The getDataInBackgroundWithBlock
won't let me set a return value other than Void in
. However, that block does add to the iconArray
as it iterates through. But once outside of the block the array is empty again. You will see in the code below the comments where the array does and does not print correctly.
调用确实连接到数据库,所有数据都在流动.它只是返回那个挂断的数组.
The call does connect to the DB, all data is flowing. It's simply returning that array that is the hang up.
class callData {
func queryImages() -> [UIImage?] {
var iconArray: [UIImage?] = []
var query: PFQuery = PFQuery(className: "QuestionMaster")
query.findObjectsInBackgroundWithBlock { (objects: [AnyObject]?, error: NSError?) -> Void in
for object in objects! {
let imageFiles = object["questionImage"] as! PFFile
imageFiles.getDataInBackgroundWithBlock({
(imageData: NSData?, error: NSError?) -> Void in
if (error == nil) {
let image = [UIImage(data: imageData!)]
iconArray += image //adds item to array correctly
}
println(iconArray) //prints correct array here
}) //getDataInBackgroundWithBlock close
println(iconArray) //does not print correct array here
} //for-loop close
}
return iconArray //returns empty array
}
}
推荐答案
当您的函数声明该块在后台执行时(在异步线程上.这意味着它将在后台加载,但也会继续执行函数的其余部分,从而返回一个空数组.
As your function states the block is executed in the background (on a asynchronous thread. This means that it will load in the background but will also continue the rest of the function thus returning an empty array.
要解决此问题,您应该在后台为块使用完成处理程序.
To fix this you should use a completion handler for your block in background.
func queryImages(onComplete:(images: [UIImage?])-> Void){
var iconArray: [UIImage?] = []
var query: PFQuery = PFQuery(className: "QuestionMaster")
query.findObjectsInBackgroundWithBlock { (objects: [AnyObject]?, error: NSError?) -> Void in
for object in objects! {
let imageFiles = object["questionImage"] as! PFFile
let imageData = imageFiles.getData()
let image = UIImage(data:imageData!)
iconArray.append(image)
println(iconArray)
}
onComplete(images: iconArray)
}
}
虽然上面的代码未经测试应该可以工作
Although untested above code should work
for 循环中的异步数据检索已被替换为同步调用以简化项目
The Asynchronous data retrieval inside your for loop has been replaced in favor of a synchronous call to ease the project
这篇关于从解析查询块返回 UIImage 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!