简体   繁体   中英

How to use variables outside ViewDidLoad( ) - Swift

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM