New value is only available in sendAsynchronousRequest - Swift

风格不统一 提交于 2019-12-02 14:59:21

问题


var arrayData: [String] = []

let bodyData = "parameter=test"

let URL: NSURL = NSURL(string: "Link to php file")
let request:NSMutableURLRequest = NSMutableURLRequest(URL:URL)
request.HTTPMethod = "POST"
request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding);
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue())
{
    (response, data, error) in
        var output = NSString(data: data, encoding: NSUTF8StringEncoding)

        self.arrayData = self.JSONParseArray(output)

        println(self.arrayData) //Print the result
}

println(self.arrayData) //Print nothing

It look like the new value is only available in sendAsynchronousRequest

Is there a way to make the new value accessible out of the sendAsynchronousRequest ?


回答1:


sendAsynchronousRequest is, as the name suggests, asynchronous. So your final println runs before the request is complete. After the completion handler runs, the new data will be available for all readers (in or outside this handler).




回答2:


sendAsynchronousRequest requires a callback passed as argument, which is executed once the asynchronous request has been completed. That's out of the linear flow in your code.

This is what happens:

  1. you call sendAsynchronousRequest
  2. the request is started, but the function returns immediately (it doesn't wait for the request to be completed)
  3. the println line is executed next (last line in your code)
  4. some time later, the asynchronous request is completed, and the closure is executed
  5. the closure assigns a value to self.arrayData

If you want to use the updated value, you have to change the logic a little bit. You can call another closure or a class method (meaning an instance method, not a static one) to post process that variable once it has been set.



来源:https://stackoverflow.com/questions/25532097/new-value-is-only-available-in-sendasynchronousrequest-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!