Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Referencing AppDelegate instance variables

People also ask

Is AppDelegate a controller?

The application delegate is a controller object. By default, it is the owner and controller of the main window -- which is a view -- in an iOS app.


For variables (usually the model data structure) which I need to access it anywhere in the app, declare them in your AppDelegate class. When you need to reference it:

YourAppDelegate *appDelegate = (YourAppDelegate *)[[UIApplication sharedApplication] delegate];
//and then access the variable by appDelegate.variable 

If I understand your question, you want to reference member variables/properties in your AppDelegate object? The simplest way is to use [[UIApplication sharedApplication] delegate] to return a reference to your object.

If you've got a property called window, you could do this:

UIWindow   *mainWindow = [[[UIApplication sharedApplication] delegate] window];
//do something with mainWindow

Here's a well defined portable alternative for iOS4.0 and up:

UIApplication *myApplication = [UIApplication sharedApplication];
UIWindow *mainWindow = [myApplication keyWindow];
UIViewController *rootViewController = [mainWindow rootViewController];

or, in one line,

UIViewController *rootViewController = [[[UIApplication sharedApplication] keyWindow] rootViewController];

Don't forget to set the window's rootViewController property (say in IB) or this will do jack.


Define a macro and use it anywhere!

#define appDelegateShared ((AppDelegate *)[UIApplication sharedApplication].delegate)

In My Code:-

UIViewController *rootViewController = appDelegateShared.window.rootViewController;