Array retuning a blank array outside of PFQuery with Parse.

廉价感情. 提交于 2019-12-02 09:52:29

This a very common misunderstanding relating to threading, the issue is what order events run:

// Runs 1st
query.findObjectsInBackgroundWithBlock {
    (objects: [AnyObject]?, error: NSError?) -> Void in
    // Runs 3rd
}
// Runs 2nd
println(placesArr)

The execution of the program doesn't halt when you call findObjectsInBackground, it finds objects: inBackground which means the heavy lifting of a network request is dispatched to a different queue so that the user can still interact with the screen. A simple way to do this would be to do:

var placesArray: [Place] = [] {
    didSet {
        // Do any execution that needs to wait for places array here.
    }
}

You can also trigger subsequent actions within the parse response block, I just personally find executing behavior dependent on a property update being executed in didSet to be a nice way to control flow.

Duncan C

Logan's answer is right in the money.

See my answer in this thread: Storing values in completionHandlers - Swift

I wrote up a detailed description of how async completion handlers work, and in the comments there is a link to a working example project the illustrates it.

query.findObjectsInBackgroundWithBlock is a block operation that performs in the background - it's asynchronous.

The line println(placesArr) actually executes before the block is finished - that's why you see nil there.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!