我在从闭包中检索数据时遇到了问题。我正在调用一个名为getWallImages的函数,该函数应该返回一个数组。我可以从闭包中打印数组的内容,但是在闭包之外,数组是空的。
import Foundation
import Parse
class WallPostQuery {
var result = [WallPost]()
func getWallImages() -> [WallPost] {
let query = WallPost.query()!
query.findObjectsInBackgroundWithBlock { objects, error in
if error == nil {
if let objects = objects as? [WallPost] {
self.result = objects
//This line will print the three PFObjects I have
println(self.result)
}
}
}
//this line prints [] ...empty array?
println(result)
return self.result
}
}问题
如何从闭包中获取值?
发布于 2015-09-09 23:20:02
这是因为println(result)在self.results = objects之前执行。闭包是异步执行的,所以它会在以后执行。尝试创建一个使用可以从闭包中调用的结果的函数:
var result = [WallPost]()
func getWallImages() {
let query = WallPost.query()!
query.findObjectsInBackgroundWithBlock { objects, error in
if error == nil {
if let objects = objects as? [WallPost] {
self.result = objects
//This line will print the three PFObjects I have
println(self.result)
self.useResults(self.result)
}
}
}
}
func useResults(wallPosts: [WallPost]) {
println(wallPosts)
}
}您的问题的另一个解决方案是创建自己的闭包,这样您就可以从该函数返回它:
var result = [WallPost]()
func getWallImages(completion: (wallPosts: [WallPost]?) -> ()) {
let query = WallPost.query()!
query.findObjectsInBackgroundWithBlock { objects, error in
if error == nil {
if let objects = objects as? [WallPost] {
self.result = objects
//This line will print the three PFObjects I have
println(self.result)
completion(wallPosts: self.result)
} else {
completion(wallPosts: nil)
}
} else {
completion(wallPosts: nil)
}
}
}
func useResults(wallPosts: [WallPost]) {
println(wallPosts)
}
}发布于 2015-09-09 23:17:48
发生的情况是,该方法在闭包执行之前返回。
从根本上说,你在管理异步回调的方式上遇到了问题。
Asynchronous vs synchronous execution, what does it really mean?
你需要在你的闭包中创建一种通知调用者的方法。您可以通过以下方式实现这一点:要求将自己的闭包作为输入参数;使用委托模式;使用通知。
https://codereview.stackexchange.com/questions/87016/swift-ios-call-back-functions
每种方法都有各自的优点和缺点,这取决于你的具体情况。开始使用异步数据获取的最简单方法是传入您自己的闭包。从那里,如果需要,您可以跳转到另一个模式,例如委托模式。
发布于 2015-09-09 23:21:08
我认为println(result)的后者是在前面调用的,因为顾名思义,findObjectsInBackgroundWithBlock是在后台执行的。
因此,您可以通过以下方式确认结果:
import Foundation
import Parse
class WallPostQuery {
var result = [WallPost]() {
didSet {
println(result)
}
}
func getWallImages() {
let query = WallPost.query()!
query.findObjectsInBackgroundWithBlock { objects, error in
if error == nil {
if let objects = objects as? [WallPost] {
self.result = objects
//This line will print the three PFObjects I have
println(self.result)
}
}
}
}
}https://stackoverflow.com/questions/32483217
复制相似问题