以下函数返回PFObjects
的数组。我遇到的问题是,当函数到达返回点时,for object in object
循环尚未完成,因此该函数返回一个空数组。
有没有办法只在循环完成后才返回并填充PF数组?
func getSelectedPosts() -> [PFObject] {
println("RUN GET SH")
var fetchResults = [PFObject]()
var user = PFUser.currentUser()!
var relation = user.relationForKey("followingPosts")
var query = relation.query()
query?.findObjectsInBackgroundWithBlock({ (object: [AnyObject]?, error: NSError?) -> Void in
if error == nil
{
for object in object!
{
fetchResults.append(object as! PFObject)
}
// NEED TO RETURN HERE, THAT IS WHEN THE LOOP IS DONE AND THE ARRAY POPULATED
}
else
{
// ERROR
}
})
return fetchResults
}
答案 0 :(得分:1)
根据umakanta的建议和关闭解释here我可以按照我打算关闭的方式使用它。
<强>功能强>
func getSelectedPosts(result: (object: [PFObject]?, error: NSError? -> Void){
println("RUN GET SH")
var fetchResults = [PFObject]()
var err = NSError()
var user = PFUser.currentUser()!
var relation = user.relationForKey("followingPosts")
var query = relation.query()
query?.findObjectsInBackgroundWithBlock({ (object: [AnyObject]?, error: NSError?) -> Void in
if error == nil
{
for object in object!
{
fetchResults.append(object as! PFObject)
}
result(object: fetchResults, error: nil)
}
else
{
println("ERROR - getSelectedPosts \(error)")
result(object: nil, error: error)
}
})
}
函数调用
getSelectedPosts { (object) -> Void in
if error != nil
{
// deal with error
}
else
{
// use fetched object
}
}
答案 1 :(得分:1)
如果函数需要一个参数来获取结果。请点击以下链接