仅在数组的获取循环完成后返回的函数

时间:2015-09-07 08:25:34

标签: swift asynchronous parse-platform

以下函数返回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
 }

2 个答案:

答案 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)

如果函数需要一个参数来获取结果。请点击以下链接

Completion Handlers