我将一些数据保存到appconle的变量appdelegate&从另一个视图控制器获取它.Below是app delegate的代码
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var navigationController: UINavigationController?
var mainDic:NSMutableDictionary?
设置mainDic的代码
func filterResponse(response:NSDictionary){
var appDelegate=AppDelegate()
appDelegate.mainDic=response.mutableCopy() as? NSMutableDictionary
}
获取字典的代码。
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
println(appDelegate.mainDic)
问题是我得到的输出为零。请让我纠正。
答案 0 :(得分:24)
这是你的错误
var appDelegate=AppDelegate() //You create a new instance, not get the exist one
您需要访问现有的AppDelegate
let appDelegate = UIApplication.shared.delegate as! AppDelegate
答案 1 :(得分:19)
Swift 4.0
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let aVariable = appDelegate.value
Swift 3.0
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let aVariable = appDelegate.someVariable
Swift 2.0
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let aVariable = appDelegate.someVariable
答案 2 :(得分:0)
func appDelegate() -> AppDelegate {
return UIApplication.sharedApplication().delegate as! AppDelegate
}