我首先尝试了这个解决方案,在我想返回的地方返回一个 bool 值。但是,由于 parse.com 函数 saveInBackgroundWithBlock() 是一个无效返回函数,我得到了错误“无效函数中意外的非无效返回值”。
func saveObjectToParse(gameLocal: Game) -> Bool {
let game = PFObject(className:"Game")
game["sport"] = gameLocal.sport.rawValue
var saved = false
game.saveInBackgroundWithBlock {
(success: Bool, error: NSError?) -> Void in
if (success) {
print("Object has been saved.")
saved = true
return saved
} else {
print("parse error")
return saved
}
}
}
因此,我尝试将 return 语句移出子函数,如下所示:
func saveObjectToParse(gameLocal: Game) -> Bool {
let game = PFObject(className:"Game")
game["sport"] = gameLocal.sport.rawValue
var saved = false
game.saveInBackgroundWithBlock {
(success: Bool, error: NSError?) -> Void in
if (success) {
print("Object has been saved.")
saved = true
} else {
print("parse error")
}
}
return saved
}
但是,这会在 saveInBackgroundWithBlock() block 执行之前返回已保存,因为它是后台进程。因此,得救永远不会是真的,即使它本来是这样的。我尝试添加一个名为 done 的 bool 标志,并尝试使用 while(!done) 循环等待,但这会卡住循环中的程序并且后台进程永远不会执行。我该如何解决这些问题?
最佳答案
我同意不需要返回 bool 值的重组,但如果你真的,真的需要这个设置,你可以同步保存你的对象(所以你的代码会等待) 像这样,
do {
try game.save()
} catch {
print(error)
}
关于swift - 如何在swift的后台进程子函数中将值返回给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33657758/