Saurabh Saurabh - 1 year ago 260
iOS Question

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

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

Leo Leo
Answer Source

This is your error

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

Try to change your code to this

func filterResponse(response:NSDictionary){
    var appDelegate= UIApplication.sharedApplication().delegate as! AppDelegate
    appDelegate.mainDic=response.mutableCopy() as? NSMutableDictionary
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download