[英]Global variable in Appdelegate in swift
我將一些數據從viewcontroller保存到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)
問題是我得到的輸出為零。請讓我正確。
這是你的錯誤
var appDelegate=AppDelegate() //You create a new instance, not get the exist one
您需要訪問現有的AppDelegate
let appDelegate = UIApplication.shared.delegate as! AppDelegate
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
func appDelegate() -> AppDelegate {
return UIApplication.sharedApplication().delegate as! AppDelegate
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.