我在从闭包中检索数据时遇到问题。我正在调用函数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
    }
}

问题
如何从闭包中获取值?

最佳答案

这是因为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)
    }

}

关于swift - Swift闭包问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32483217/

10-15 03:19