Saurabh Mishra
Saurabh Mishra

Reputation: 881

Global variable in Appdelegate in 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.

Upvotes: 15

Views: 26106

Answers (3)

Sankalap Yaduraj Singh
Sankalap Yaduraj Singh

Reputation: 1199

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

Upvotes: 23

Leo
Leo

Reputation: 24714

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

Upvotes: 31

tania_S
tania_S

Reputation: 1370

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

Upvotes: 1

Related Questions