Reputation: 1141
I am doing an HTTP request with NSURLSession
, which requires a closure that will execute at the end of the request. From within the closure I am trying to call a function and pass the returnList
object to that function.
The Problem: When I print out the list with the callback()
function, it is empty, even though I have assigned a value to the list object inside the closure. What is the cause of this behaviour and what do I have to do to pass an object to a function that is called inside a closure?
var returnList = [ReturnList]()
...
...
func httpRequestFunction(callback: ([ReturnList])->()){
let task = NSURLSession.sharedSession().dataTaskWithURL(url){(data, response, error) in
if error != nil {
//TODO do some error handling
return
}
var xmlUtil = XMLUtil(data: data)
self.returnList = xmlUtil.parseXML()
println(self.returnList.count) // returns 1
callback(self.returnList) /*the callback prints returnList.count which is then 0 */
}
task.resume()
}
Upvotes: 0
Views: 72
Reputation: 535159
What you're describing is not normal, so something else must be going on. For example:
typealias ReturnList = Int
var returnList = [ReturnList]()
func httpRequestFunction(callback: ([ReturnList])->()) {
self.returnList = [1,2,3]
print(self.returnList.count) // prints 3
callback(self.returnList) // prints 3
}
func test() {
httpRequestFunction {
list in
print(list.count)
}
}
It works perfectly. Since that isn't the sort of result you're getting, you must be doing something else wrong - but there's no way of knowing what it is, since you refuse to show any more code.
For example, you say that callback
prints returnList.count
, but of course it better not be printing self.returnList.count
- it needs to print the count of the list that it got as its parameter (as in my example above). But you refuse to show it, so how do I know you're doing it right? And so on.
Another source of difficulty is that you are accessing an instance variable, self.returnList
, from within an HTTP callback. So who knows what thread we are on? If this is happening on a background thread, some other thread could come along and change self.returnList
between the time we print
it and the time we call callback
in the very next line! So again, further details would be needed.
Upvotes: 1