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。
- 我从哪里可以获得CommonCrypto / CommonCrypto文件?
- xcode gm ios 8 gm swift今天扩展崩溃在模拟器和设备:库未加载:@ rpath / libswiftCore.dylib
- 如何禁用Alamofire中的caching
- iOS旋转videoAVAsset avfoundation
- 如何获得快速应用程序中的keyWindow引用?
- 如何在Swift中使用enum和switch()与UITableViewController
- Swift – 如何将酒吧附加到表视图的顶部?
- Firebase – 如何在observeEventType = Value中获取关键值
- iOS 9 CoreData / ICloud – URL中没有这样的文档