引用应用委托实例变量

我有一个基于导航应用程序模板的项目。 方法 -applicationDidFinishLoading:-applicationWillTerminate:位于 AppCommittee 中。在这些方法中,我加载和保存应用程序数据,并将其存储在一个实例变量中(它实际上是一个对象图)。

当应用程序加载时,它加载 MainWindow.xib,其中有一个 NavigationController,而 NavigationController 又有一个 RootViewController。RootViewControllernibName属性指向 RootView (我的实际控制器类)。

在我的类中,我希望引用我在 -applicationDidFinishLoading:方法中创建的对象,这样我就可以获得对它的引用。

有人能告诉我怎么做吗?我知道如何在以编程方式创建的对象之间进行引用,但是我似乎不知道如何返回,因为中间的步骤是在 NIB 文件中完成的。

63951 次浏览

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

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

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;