0

If I have declared a variable withing ViewDidLoad(). Is there a way to access that variable outside of ViewDidLoad( )?

I have retrieved and stored the JSON data from an API. I am able to access the variable 'hourlyInfo' within the ViewDidLoad( ), but not outside of it. Should I use global variables? Or am I in approaching the problem wrongly to begin with?

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

    //getting the data from URL:
    let mainAddress = NSURL(string: "https:.......") 


    //Now, getting the data syncronously by creating a session object::
    let sharedSession = NSURLSession.sharedSession()
    let downloadTask: NSURLSessionDownloadTask =
    sharedSession.downloadTaskWithURL(mainAddress!, completionHandler: {
        (location:NSURL!, response:NSURLResponse!, error: NSError!) -> Void in

        if error == nil {
            //Now, creating a dataObject for the task:
            let dataObject = NSData(contentsOfURL: location)


            //getting a formated dictionary of the data from URL:
            var weatherDictionary: NSDictionary = NSJSONSerialization.JSONObjectWithData(dataObject!, options: nil, error: nil) as NSDictionary //added '!' to NSdata for now





   var hourlyInfo = hourlyData(weatherDictionary: weatherDictionary) 

   println(hourlyInfo.hourPop1)//testing                         


        }



    })

    downloadTask.resume()
rmaddy
  • 314,917
  • 42
  • 532
  • 579
bhppl
  • 7
  • 5

1 Answers1

2

Since you are creating hourlyInfo inside viewDidLoad, it is only available within viewDidLoad, and even more specifically, the downloadTaskWithURL block. You can create a property at the top of the class to hold the hourlyInfo, but hourlyInfo will only be set when the block has completed. Moreover, since you will be using a property and refer to self.hourlyInfo inside the block, you should create a weak self variable as described here: How to Correctly handle Weak Self in Swift Blocks with Arguments.

Community
  • 1
  • 1
Josh Gafni
  • 2,831
  • 2
  • 19
  • 32