swift 2解析来自findObjectsInBackgroundWithBlock的数据

时间:2015-11-08 20:02:04

标签: swift parse-platform

我在这里有一个带有parse.com代码的快速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

1 个答案:

答案 0 :(得分:0)

这是因为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来执行last,请尝试在同一个闭包中实现代码。

您还可以参考堆栈答案Synchronous vs Asynchronous。问题是关于目标C,然而,原则与Swift相同。

此外,如果您想了解Swift中的Concurrency,可以参考之前的Stack回答How to do multithreading, concurrency or parallelism in iOS Swift