gpt4 book ai didi

swift - 全局变量重置的定义

转载 作者:行者123 更新时间:2023-11-30 10:12:48 26 4
gpt4 key购买 nike

我有一个类,旨在从 API 获取特定日期的温度数据并将其添加到字典中。 API 的 URL 存储在名为 baseURL 的全局变量中。它在开始时被定义为空字符串,但后来被更改。我的类(class)如下:

import UIKit
import Foundation
typealias ServiceResponse = (JSON, NSError?) -> Void

class WeatherManager: NSObject {

var baseURL: String = ""
var data: String = ""
static let sharedInstance = WeatherManager()


func getRandomUser(onCompletion: (JSON) -> Void) {
println("Starting getRandomUser")
let route = self.baseURL
println(self.baseURL)
makeHTTPGetRequest(route, onCompletion: { json, err in
onCompletion(json as JSON)
})
}

func makeHTTPGetRequest(path: String, onCompletion: ServiceResponse) {
let request = NSMutableURLRequest(URL: NSURL(string: path)!)

let session = NSURLSession.sharedSession()

let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
let json:JSON = JSON(data: data)
onCompletion(json, error)
if error != nil {
println("No Error")
} else {
println("Error")
}
})
task.resume()
}

func addData() {
WeatherManager.sharedInstance.getRandomUser { json in
var jsonData = json["response"]["version"]
self.data = "\(jsonData)"
dispatch_async(dispatch_get_main_queue(),{
let alert = UIAlertView()
alert.title = "Weather Data Update"
if self.data != "null" {
println("Value:\(self.data)")
alert.message = "The weather data was updated successfully."
alert.addButtonWithTitle("OK")
alert.show()
} else {
println("Error Reading Data")
println(self.data)
alert.message = "HealthTrendFinder encountered an error while updating data."
alert.addButtonWithTitle("OK")
alert.show()
}
})
}
}

func updateWeatherHistory() {
println(self.baseURL)
let calendar: NSCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
println("Weather Updating...")
// This sets the start date to midnight of the current date if no start date has been set.
if StorageManager.getValue(StorageManager.StorageKeys.WeatherStartDate) == nil {
let startDate: NSDate = calendar.startOfDayForDate(NSDate())
StorageManager.setValue(startDate, forKey: StorageManager.StorageKeys.WeatherStartDate)

}

// This adds a data array if it hasn't been created yet.
if StorageManager.getValue(StorageManager.StorageKeys.WeatherData) == nil {
StorageManager.setValue([:], forKey: StorageManager.StorageKeys.WeatherData)

}

var weatherData: [NSDate: NSObject] = StorageManager.getValue(StorageManager.StorageKeys.WeatherData)! as! [NSDate : NSObject]
let startMidnight: NSDate = StorageManager.getValue(StorageManager.StorageKeys.WeatherStartDate) as! NSDate
let currentMidnight: NSDate = calendar.startOfDayForDate(NSDate())
let daysFromStartDate: Int = calendar.components(NSCalendarUnit.CalendarUnitDay, fromDate: startMidnight, toDate: currentMidnight, options: nil).day
println("Starting Loop")
for i: Int in 0..<daysFromStartDate {

let dateToBeExamined: NSDate = calendar.dateByAddingUnit(NSCalendarUnit.CalendarUnitDay, value: i, toDate: startMidnight, options: nil)!
if weatherData[dateToBeExamined] == nil {
let calendarUnits: NSCalendarUnit = .CalendarUnitDay | .CalendarUnitMonth | .CalendarUnitYear
let components = NSCalendar.currentCalendar().components(calendarUnits, fromDate: dateToBeExamined)
var month: String
var day: String
if components.month < 10 {
month = "0\(components.month)"
} else {
month = "\(components.month)"
}
if components.day < 10 {
day = "0\(components.day)"
} else {
day = "\(components.day)"
}
var dateString = "\(components.year)\(month)\(day)"
self.baseURL = "http://api.wunderground.com/api/91e65f0fbb35f122/history_\(dateString)/q/OR/Portland.json"
println(self.baseURL)
var get: () = WeatherManager.sharedInstance.addData()
println(get)
weatherData[dateToBeExamined] = self.data




// There is no data for the NSDate dateForInspection. You need to pull data and add it to the dictionary.
} else {
// Data exists for the specified date, so you don't need to do anything.
}
}
println("Loop has finished or been skipped")

}

}

问题是,在将 baseURL 设置为 URL 后,执行 getRandomUser 时,baseURL 会恢复为空字符串。为什么会发生这种情况?如何解决?

最佳答案

您的代码过于复杂,在没有更多信息的情况下很难诊断问题。但这里有一个建议:

尝试让 WeatherManager 无法实例化多个实例。单例:

class WeatherManager {

private static let _sharedInstance = WeatherManager()

private init() { super.init() }

static func sharedInstance() -> WeatherManager {
return _sharedInstance
}
}

当您在外面工作时 WeatherManager ,您可以通过调用来访问它:

let wm = WeatherManager.sharedInstane()

然后,当你在 WeatherManager 里面工作时,确保您的所有引用均指向 self - 即 self.baseURL = ...self.updateWeatherHistory() ,而不是 WeatherManager.sharedInstance.baseURL = ...

虽然你的代码很复杂,但我认为发生的事情是你实际上有两个 WeatherManager 实例在玩耍中。您正在设置 baseURL 的值在其中一个上,但不在另一个上。如果你希望它是一个单例,你需要让它不可能创建多个。

关于swift - 全局变量重置的定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31995165/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com