Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global variable in Appdelegate in swift

Tags:

ios

swift

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

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

Code to set the 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.

like image 568
Saurabh Mishra Avatar asked Aug 19 '15 09:08

Saurabh Mishra


People also ask

How do you declare a global variable in Swift?

Here you can see section is a global variable we have defined, inside a class but outside a function. We can use an access modifier prefixed with the global variable as per the need. You can also define a global variables as static by prefixing static keyword.

What is AppDelegate used for in Swift?

Overview. Your app delegate object manages your app's shared behaviors. The app delegate is effectively the root object of your app, and it works in conjunction with UIApplication to manage some interactions with the system.

What is SceneDelegate and how is it different from a AppDelegate?

AppDelegate is responsible for handling application-level events, like app launch and the SceneDelegate is responsible for scene lifecycle events like scene creation, destruction and state restoration of a UISceneSession.


2 Answers

This is your error

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

You need to access the exiting AppDelegate

let appDelegate = UIApplication.shared.delegate as! AppDelegate
like image 174
Leo Avatar answered Sep 21 '22 18:09

Leo


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
like image 39
Sankalap Yaduraj Singh Avatar answered Sep 19 '22 18:09

Sankalap Yaduraj Singh