swift 2 从 findObjectsInBackgroundWithBlock 解析数据

标签 swift parse-platform

我这里有一个带有 parse.com 代码的 swift 2

问题是代码在//1 之前打印//2 这造成了一个问题,我无法在其他方法或其他地方使用该数组 这是代码

 var myStudent:Student = Student ()

        let query = PFQuery(className: "Students")
                query.findObjectsInBackgroundWithBlock { (objects: [AnyObject]?, error:NSError?) -> Void in

                    var the_array = objects as! AnyObject

                    for i in 0...the_array.count-1
                    {

                myStudent.NameStudent = the_array[i].valueForKey("name") as! String
                self.myStudentsArray.append(myStudent)
                        print(self.myStudentsArray.count) //1

            }
        }
        print(self.myStudentsArray.count) //2

最佳答案

这是因为 findObjectsInBackgroundWithBlock 在后台线程上异步运行。

解决方案是在闭包内调用任何需要准确 .count 的函数,这样您就可以确保获得正确的 Array.count。

var myStudent:Student = Student ()

    let query = PFQuery(className: "Students")
            query.findObjectsInBackgroundWithBlock { (objects: [AnyObject]?, error:NSError?) -> Void in

                var the_array = objects as! AnyObject

                for i in 0...the_array.count-1
                {

            myStudent.NameStudent = the_array[i].valueForKey("name") as! String
            self.myStudentsArray.append(myStudent)
                    print(self.myStudentsArray.count) //1
          //Call any function that needs the students count here. This would 
         //be the only way you can guarantee you will get the correct count within the closure.

        }
    }
    print(self.myStudentsArray.count) //2

这是一个关于 Grand Central Dispatch (GCD) - RayWenderlich 的很棒的教程。如果您需要 print 2 最后执行,请尝试在同一个闭包中实现代码。

也可以引用Stack回答Synchronous vs Asynchronous 。问题是关于 Objective C 的,但是原理和 Swift 是一样的。

此外,如果你想了解 Swift 中的并发,可以引用之前的 Stack 回答 How to do multithreading, concurrency or parallelism in iOS Swift

关于swift 2 从 findObjectsInBackgroundWithBlock 解析数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33598396/

相关文章:

ios - 快速边框颜色

swift - Swift 3.0 上没有这样的模块 'SwiftyJSON'

安卓。解析.com : Invalid Session Token

Java/解析错误。试图从 android sdk 发送到 Parse

ios - -[UIViewController tableView :numberOfRowsInSection:]: unrecognized selector sent to instance 0x7ff437517770

swift - 错误语法 UIColor(CGColor : selectedButton? .layer.backgroundColor) Swift

iOS:使用 anchor 以编程方式将 UIImageView 与底部对齐

ios - 如何从 iOS 中的解析中获取用户特定推送通知的历史记录?

扩展 ParsePushBroadcastReceiver 通知的 Android 自定义类

ios - 在大类上解析 countObjectsInBackground