Xcode7 swift 函数需要多少时间?比赛条件?

Xcode7 swift function needs to much time? Race condition?

我的 Xcode 7 项目中有一个关于 Facebook 的问题。 尝试通过图形请求检索我的数据时,函数 returnUserData 完成得太晚了?

//...
returnUserData()
print("finished")
//...

这是函数:

func returnUserData() {
        let graphRequest : FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, name, first_name, last_name, email"])
        graphRequest.startWithCompletionHandler({ (connection, result, error) -> Void in
        if error == nil
            {
                //print("fetched user: \(result)")
                print("start");
                self.username = result.valueForKey("name") as! NSString
                //NSUserDefaults.standardUserDefaults().setObject(self.username, forKey: "name")
                //NSUserDefaults.standardUserDefaults().synchronize()
                print("1: " + (self.username as String))
            }
        else if (error != nil)
            {
                // Process error
                print("Error: \(error)")
            }
        })

    }

但是这是,怎么回事,看顺序:

finished
start
1: My Name

我该如何防止这种情况发生?

那是因为 graphRequest.startWithCompletionHandler 调用是异步的。如果你在代码中的 returnUserData()print("finished") 处放置断点,你会看到 graphRequest.startWithCompletionHandler 执行后,该函数将立即 return 到 print("finished") 语句和完成处理程序中的语句不会执行(在 graphRequest.startWithCompletionHandler 调用后立即执行)。

为了正确处理它,您可以在 completionHandler 中编写处理代码 [例如:print("finished")],或者编写一个回调函数,您可以在处理/验证服务器响应后将数据传递给该回调函数.