ios Appdelegate中的全局变量迅速

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32092243/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 07:19:47  来源:igfitidea点击:

Global variable in Appdelegate in swift

iosswift

提问by Saurabh Mishra

I am saving some data to a variable of appdelegate from a viewcontroller & fetching it from another view controller.Below is the code of app delegate

我正在将一些数据从视图控制器保存到 appdelegate 变量并从另一个视图控制器获取它。下面是应用程序委托的代码

class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var navigationController: UINavigationController?
var mainDic:NSMutableDictionary?

Code to set the mainDic

设置 mainDic 的代码

func filterResponse(response:NSDictionary){

    var appDelegate=AppDelegate()
    appDelegate.mainDic=response.mutableCopy() as? NSMutableDictionary
}

Code to fetch the dictionary.

获取字典的代码。

let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
println(appDelegate.mainDic)

The issue is I am getting the output nil.Please make me correct.

问题是我得到的输出为零。请纠正我。

回答by Leo

This is your error

这是你的错误

var appDelegate=AppDelegate() //You create a new instance, not get the exist one

You need to access the exiting AppDelegate

您需要访问现有的 AppDelegate

let appDelegate = UIApplication.shared.delegate as! AppDelegate

回答by Sankalap Yaduraj Singh

Swift 4.0

斯威夫特 4.0

 let appDelegate = UIApplication.shared.delegate as! AppDelegate 
 let aVariable = appDelegate.value

Swift 3.0

斯威夫特 3.0

let appDelegate = UIApplication.shared.delegate as! AppDelegate
let aVariable = appDelegate.someVariable

Swift 2.0

斯威夫特 2.0

let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let aVariable = appDelegate.someVariable

回答by tania_S

func appDelegate() -> AppDelegate {
  return UIApplication.sharedApplication().delegate as! AppDelegate
}