【发布时间】:2015-11-11 18:50:40
【问题描述】:
我首先尝试了这个解决方案,在我想要返回它的地方返回一个布尔值。但是,由于 parse.com 函数 saveInBackgroundWithBlock() 是一个 void 返回函数,我收到错误“Unexpected non-void return value in void function”。
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() 块执行之前返回已保存,因为它是一个后台进程。因此,得救永远不会是真的,即使它是有意的。我尝试添加一个名为 done 的布尔标志,并尝试使用 while(!done) 循环等待,但这会将程序冻结在循环中,并且后台进程永远不会执行。我该如何解决这些问题?
【问题讨论】:
-
可能性包括让任何调用
saveObjectToParse传入块以针对成功或失败情况执行或在保存完成时对通知做出反应。
标签: swift asynchronous parse-platform background-process