如果我声明了一个带有ViewDidLoad()
的变量。有没有办法在ViewDidLoad( )
之外访问该变量?
我已经从API检索并存储了JSON数据。我可以在ViewDidLoad( )
中访问变量'hourlyInfo',但不能访问它之外的变量'hourlyInfo'。我应该使用全局变量吗?或者我是否在开始时错误地解决了这个问题?
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()
答案 0 :(得分:1)
由于您在viewDidLoad
内创建了hourlyInfo,因此只能在viewDidLoad
内使用,更具体地说,downloadTaskWithURL
块。您可以在类的顶部创建一个属性来保存hourlyInfo,但只有在块完成时才会设置hourlyInfo。此外,由于您将使用属性并在块内引用self.hourlyInfo,您应该创建一个弱自变量,如下所述:How to Correctly handle Weak Self in Swift Blocks with Arguments。