我这里有一个带有 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/