AppDelegate instance variable reference

I have a project based on a navigation based application template. AppDelegate uses the -applicationDidFinishLoading: and -applicationWillTerminate: methods. In these methods, I load and save the application data and save it in the instance variable (this is actually a graph object).

When the application loads, it loads MainWindow.xib, which has a NavigationConroller, which in turn has a RootViewController. The RootViewController nibName property points to RootView (my actual controller class).

In my class, I want to refer to the object that I created in the -applicationDidFinishLoading: method -applicationDidFinishLoading: that I can get a reference to it.

Can someone tell me how to do this? I know how to refer between objects that I created programmatically, but I cannot understand that I need to reverse my path, given that the middle step was made from a NIB file.

+82
iphone cocoa-touch
Oct 23 '08 at 23:27
source share
4 answers

For the variables (typically model data structures) that I need to get anywhere in the application, 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 
+203
Oct 24 '08 at 3:14
source share

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

If you have a property called a window, you can do this:

 UIWindow *mainWindow = [[[UIApplication sharedApplication] delegate] window]; //do something with mainWindow 
+15
Oct 23 '08 at 23:51
source share

Here's a definitely portable alternative for iOS4.0 and higher:

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

or, in one line,

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

Do not forget to set the window property rootViewController (say, in IB), or the jack will do it.

+11
Feb 27 '11 at 11:13
source share

I define a macro and use it like this: -

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

In my code: -

 appDelegateShared.myVariable=anotherVariable; 
+1
Dec 23 '16 at 10:31
source share



All Articles