使用 Parse 在 PFQuery 之外重新调整空白数组的数组. [英] Array retuning a blank array outside of PFQuery with Parse.
问题描述
数组在 PFQuery 之外返回空数组.出于某种原因,项目在编译时没有被传递到数组.
Array returning a blank array when outside of the PFQuery. For some reason, the items are not being passed to the array when compiled.
class DriverViewController: UIViewController {
var placesArr : Array<Place> = []
override func viewDidLoad() {
super.viewDidLoad()
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
var query = PFQuery(className:"places")
query.whereKey("username", equalTo:"email@email.com")
query.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]?, error: NSError?) -> Void in
if error == nil {
println("Successfully retrieved (objects!.count) scores.")
if let objects = objects as? [PFObject] {
for object in objects {
let x = Place(aIdent: (object["Ident"] as! Int), aName: (object["name"] as! String), aAddress: (object["originAddress"] as! String), aCity: (object["originCity"] as! String), aCategoryName: (object["catName"] as! String), aLat: (object["aLat"] as! String), aLng: (object["aLng"] as! String))
self.placesArr.append(x)
println(placesArr) //****It works here and prints an array****
}
}
} else {
// Log details of the failure
println("Error: (error!) (error!.userInfo!)")
}
}
println(placesArr) //****But here it returns a blank array and this is where I need it to return an array****
推荐答案
这是一个非常常见的与线程相关的误解,问题是事件运行的顺序:
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)
当您调用 findObjectsInBackground
时,程序的执行不会停止,它会查找对象:inBackground
这意味着繁重的网络请求被分派到不同的队列,以便用户仍然可以与屏幕交互.一个简单的方法是这样做:
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.
}
}
您还可以在解析响应块中触发后续操作,我个人认为依赖于在 didSet
中执行的属性更新的执行行为是一种控制流程的好方法.
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.
这篇关于使用 Parse 在 PFQuery 之外重新调整空白数组的数组.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!