简体   繁体   English

如何在ViewDidLoad()之外使用变量-Swift

[英]How to use variables outside ViewDidLoad( ) - Swift

If I have declared a variable withing ViewDidLoad() . 如果我已经使用ViewDidLoad()声明了一个变量。 Is there a way to access that variable outside of ViewDidLoad( ) ? 有没有办法在ViewDidLoad( )之外访问该变量?

I have retrieved and stored the JSON data from an API. 我已经从API检索并存储了JSON数据。 I am able to access the variable 'hourlyInfo' within the ViewDidLoad( ) , but not outside of it. 我可以在ViewDidLoad( )访问变量“ hourlyInfo”,但不能在其外部访问。 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. 由于您是在viewDidLoad内部创建hourlyInfo,因此仅在viewDidLoad可用,更具体地说,在downloadTaskWithURL块中可用。 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. 您可以在类的顶部创建一个属性来保存hourlyInfo,但是hourlyInfo仅在块完成时设置。 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 . 此外,由于您将使用属性并在块内引用self.hourlyInfo,因此您应按如下所述创建一个弱的self变量: 如何正确处理带有参数的Swift块中的弱自我

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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