将数据从函数返回到全局变量 (Swift)

Returning Data from function into a Global Variable (Swift)

我正在尝试 return 结果并能够从此函数访问结果数组。函数中的一切都在工作,但是我无法 return 任何东西或访问结果或从闭包外部在函数内部创建的任何变量。我想从闭包外部(ViewDidLoad 内部)访问 result.valueForKey("id")。我怎样才能做到这一点? (请参阅 "This works" 和 "This doesn't work" 部分..

 class ViewController: UIViewController, FBSDKLoginButtonDelegate {

 var facebookid: NSString = ""
 var username: NSString = ""
 var userEmail:NSString = ""

 override func viewDidLoad() {
  super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.

if (FBSDKAccessToken.currentAccessToken() == nil)
{
    let loginView : FBSDKLoginButton = FBSDKLoginButton()
    self.view.addSubview(loginView)
    loginView.center = self.view.center
    loginView.readPermissions = ["public_profile"]
    loginView.delegate = self

} else {

    returnUserData()

    println("test") // This works (gets printed)
    println(facebookid)  // This doesn't work (not even nil)
    println(self.username) // This doesn't work either (not even nil)

  }
}



func returnUserData()
{

let graphRequest : FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: nil)
graphRequest.startWithCompletionHandler({ (connection, result, error) -> Void in

    if ((error) != nil)
    {
        // Process error
        println("Error: \(error)")
    }
    else
    {

        self.facebookid = result.valueForKey("id") as NSString!
        self.username = result.valueForKey("name") as NSString!
        self.userEmail = result.valueForKey("email") as NSString!
        println(result) // This works
        println(facebookid) // This works


    }
})
}

原因是您在 returnUserData 中的请求不是同步函数,因此它会在您对这些数据调用 println() 后更新您的数据。您应该在 iOS.

中阅读有关多线程的更多信息
returnUserData()  //it calls returnUserData() to update your facebookid & self.username. However, in `returnUserData`, it use `FBSDKGraphRequest` to get facebook datas. As FBSDKGraphRequest retrieve datas from internet connection (and it takes time to finish), it is designed to retrieve datas in async, to avoid blocking your function.

//So, you risk to finish your returnUserData function before the process of FBSDKGraphRequest is terminated (and the completionHandler is called to update your data). 

println("test") // This works (gets printed)
println(facebookid)  // This doesn't work (not even nil) //this is called before your completionHandler is invoked, you don't have new data
println(self.username) // This doesn't work either (not even nil) //this is called before your completionHandler is invoked too, you don't have new data.

要解决该问题,您应该在 completionHandler

中处理 facebookidself.username 的新值