是的..当我开始 iPhone 开发时.. rootViewController 的事情也让我陷入了循环。但这真的很简单。
当应用程序启动时,我在我的应用程序委托类中创建了一个 UIWindow 对象。另外,在那个类中,我有一个 UIWindow 类型的属性,称为 window;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
UIWindow *w = [[UIWindow alloc]initWithFrame:[[UIScreen mainScreen]bounds]];
self.window=w;
[w release];
// other code here...
}
然后我创建一个UIViewController
其view
将成为窗口层次结构中的第一个视图,这可以称为“根视图控制器”。
令人困惑的部分是......通常我们创建一个UINavigationController
作为“根视图控制器”并且导航控制器有一个 init 方法要求一个“RootViewController”,这是它将放置在其堆栈中的第一个视图控制器。
因此,窗口获得了一个“根视图控制器”,即UINavigationController
,它还有一个 RootViewController,它是您要显示的第一个视图控制器。
一旦你把它理清了,一切都说得通了..我认为:-)
这是一些可以完成所有工作的代码..(取自我面前打开的项目)
//called with the app first loads and runs.. does not fire on restarts while that app was in memory
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
//create the base window.. an ios thing
UIWindow *w = [[UIWindow alloc]initWithFrame:[[UIScreen mainScreen]bounds]];
self.window=w;
[w release];
// this is the home page from the user's perspective
//the UINavController wraps around the MainViewController, or better said, the MainViewController is the root view controller
MainViewController *vc = [[MainViewController alloc]init];
UINavigationController *nc = [[UINavigationController alloc]initWithRootViewController:vc];
self.navigationController=nc; // I have a property on the app delegate that references the root view controller, which is my navigation controller.
[nc release];
[vc release];
//show them
[self.window addSubview:nc.view];
[self.window makeKeyAndVisible];
return YES;
}