我正在为Swift中的测试创建一个应用程序,我正在使用Parse来处理后端。主要有两个"对象"我在Parse中使用的类型:测试和问题。每个Test对象都包含一个Question对象数组,名为" questions"。我需要使用getObjectInBackgroundWithId方法捕获测试对象的问题数组,因为我有测试的objectId值,并将其保存到我之前在方法中声明的数组中。当我从闭包内部方法的开头将数组分配给我的问题数组时,我打印它,它似乎已被正确复制,但是当我在闭包之外打印它时,它还没有被复制。这是方法:
@IBAction func endTestPressed(sender: UIButton)
{
let lab = self.pinLabel.text!
var questions = [PFObject]()
let query = PFQuery(className:"Test")
query.getObjectInBackgroundWithId(lab.substringFromIndex(advance(lab.startIndex,5)))
{
(test: PFObject?, error: NSError?) -> Void in
if error == nil && test != nil
{
questions = test?["questions"] as! [PFObject]
print("Inside of closure: \(questions)")
}
else
{
print(error)
}
}
print("Outside of closure: \(questions)")
}
如何将Parse中的数组保存为闭包前方法中声明的数组?
答案 0 :(得分:1)
并不是数组在闭包外部是空的,发生的是getObjectInBackgroundWithId在后台发生,你的应用程序的其余部分仍在运行,所以你先打印外部println命令,而不是结果返回从后台线程中它只运行完成块
@IBAction func endTestPressed(sender: UIButton)
{
let lab = self.pinLabel.text!
var questions = [PFObject]()
let query = PFQuery(className:"Test")
query.getObjectInBackgroundWithId(lab.substringFromIndex(advance(lab.startIndex,5)))
{
//Run when the getObjectInBackgroundWithId return with the results
(test: PFObject?, error: NSError?) -> Void in
if error == nil && test != nil
{
questions = test?["questions"] as! [PFObject]
print("Inside of closure: \(questions)") //this happen after the print outside the closure as the request happens in the backgroun
}
else
{
print(error)
}
}
//Application continue run while the getObjectInBackgroundWithId retrives data from Parse.com
print("Outside of closure: \(questions)") //This will happen first and the array is not populate yet
}