Mohamed Horani
Mohamed Horani

Reputation: 554

Variables goes nil after execution of block

I'm having difficulty assigning a value after execution of a closure.

The problem is in //step4. It prints the contents and it captures no nil, but at //step5 it prints Nil.

I tried to creating a class and assigning the values within the HTTP Request, but no change.

My code:

var x: String!override func viewDidLoad() {
    super.viewDidLoad()
    //1
    let urlAsString = "http://date.jsontest.com/"
    let url = NSURL(string: urlAsString)!let urlSession = NSURLSession.sharedSession()
    //2
    let jsonQuery = urlSession.dataTaskWithURL(url, completionHandler: {
        data, response, error - > Void in
        if error != nil {
            println(error.localizedDescription)
        }
        var err: NSError ?
        //3
        var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: & err) as!NSDictionary
        if err != nil {
            println("JSON Error \(err!.localizedDescription)")
        }
        //4
        let jsonDate = jsonResult["date"] as!String
        let jsonTime = jsonResult["time"] as!String
        //Step 4
        //let's Assume
        x = jsonDate
        println("Inside \(x)") // Prints Date :)
        dispatch_async(dispatch_get_main_queue(), {
            self.dateLabel.text = jsonDate
            self.timeLabel.text = jsonTime
        })
    }) //end of JsonQuery
    jsonQuery.resume()
    //Step 5
    println("Outside \(x)") // Prints nil
}

Upvotes: 0

Views: 103

Answers (2)

Jonah
Jonah

Reputation: 17958

Your "step 5" will likely execute before steps 3 or 4. Calling resume does not block and wait for the response to compete so you execute step 5 before the completion block is called.

Upvotes: 0

gnasher729
gnasher729

Reputation: 52538

Your web request is an asynchronous request. That means it will finish, and the completion block will be called, at some point in the future. Some time long after you call jsonQuery.resume(). Some time long after your whole function returns.

Your variable doesn't go back to nil after the call - you check it long before it is ever set to nil. It is the job of your completion block to do everything that is necessary to process the data and store the results.

Upvotes: 1

Related Questions