swift - 如何在swift的后台进程子函数中将值返回给函数

标签 swift asynchronous parse-platform background-process

我首先尝试了这个解决方案,在我想返回的地方返回一个 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/

相关文章:

ios - 单元格上的自定义表格 View 滚动问题

ios - 点击时 UIBarButtonItem 不调用另一个类中的函数

javascript - 等待事件时异步等待 - node.js

c# - 如何从模拟对象返回 IQueryable<TEntity> 对象?

ios - 转换为字符串的任何对象

ios - 解析无效 session token 错误1.8.2

swift - 在 CloudKit 中保存对象数组

ios - 为单个 ViewController/UIcollectionView 使用多个库

c# - 接收 : Piecing together multiple IObservable web requests

java - Parse.com 查询 findInBackground 不返回任何数据