Swift,parse.com:如何从查询中传递数据

我有这样的查询parse.com。 为什么numObjectsvariables在findObjectsInBackgroundWithBlock内部具有不同的值,并且函数退出

func searchUserInParse () -> Int { var numObjects : Int = 0 // the num return objects from query var query = PFQuery(className:"Bets") query.whereKey("user", equalTo: "Bob") query.findObjectsInBackgroundWithBlock { (objects: AnyObject[]!, error: NSError!) -> Void in if !error { numObjects = objects.count println(numObjects) // at this point the value = 1 } else { // Log details of the failure NSLog("Error: %@ %@", error, error.userInfo) } } println(numObjects) // at this point the value = 0 return numObjects } 

而不是使用asynchronous运行的findObjectsInBackgroundWithBlock ,请尝试使用同步运行的findObjects

 //Set up query... var objects = query.findObjects() numObjects = objects.count println(numObjects) 

然后在运行你的函数时,像这样做:

 dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) { //Search users searchUserInParse() dispatch_async(dispatch_get_main_queue()) { //Show number of objects etc. } } 

这是asynchronous代码的本质,你的函数将运行外部代码完成,然后一段时间(取决于连接速度和查询的复杂性)完成块将运行。

你的调用代码应该做如下的事情:

  • 创build查询
  • 用完成块开始查询
  • 显示一个加载animation
  • 返回(查询结果仍然未知)

那么你应该考虑块的内部:

  • 检查错误
  • 更新UI绑定的值
  • 告诉UI刷新

你不能有一个返回计数的函数,但是你可以写一个函数,把一个完成块作为参数,并在查询完成块中执行它。 虽然这有点高级

query.findObjectsInBackgroundWithBlock将被asynchronous执行,在获取对象之后调用完成块。 因此块之后的代码首先调用numObjects值为0。