New value is only available in sendAsynchronousRequest - Swift

后端 未结 2 2024
没有蜡笔的小新
没有蜡笔的小新 2021-01-25 09:35
var arrayData: [String] = []

let bodyData = \"parameter=test\"

let URL: NSURL = NSURL(string: \"Link to php file\")
let request:NSMutableURLRequest = NSMutableURLReque         


        
相关标签:
2条回答
  • 2021-01-25 09:55

    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).

    0 讨论(0)
  • 2021-01-25 09:59

    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.

    0 讨论(0)
提交回复
热议问题