不知道是不是有人和我一样,有着不好的习惯,写着写着代码,又觉得用storyBoard要节省好多时间和垃圾代码,所以立马转过去New一个storyBoard。如果你也这样,那么接下来的这个惨痛教训希望你引以为戒。
我们知道,如果我用纯代码的方式来实现一个App,那么在
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions函数里面,你应该自己初始化window和指定一个rootViewController。
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Override point for customization after application launch.
self.window.backgroundColor = [UIColor whiteColor];
ViewController *vc=[ViewController alloc] init];
self.window.rootViewController=vc;
同时,如果你还想加入NavigationController的话,你应该这样做:
@property(strong,nonatomic)UINavigationController *navController;
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Override point for customization after application launch.
self.window.backgroundColor = [UIColor whiteColor];
self.navController=[[UINavigationController alloc] initWithRootViewController:[[ViewController alloc] init]];
self.window.rootViewController=self.navController;
这样做是没有问题的,程序启动的时候会以ViewController的实例作为第一页面。
如果用storyBoard来做,那就so easy了。例如为一个ViewController加入UINavigationController,你只需要回到storyBoard,Embed in->NavigationController,这时ViewController会作为rootViewController。通过storyBoard的方式建立project,此时- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions函数只有一句:return Yes。
运行一下,会提示如下warning:
“Applications are expected to have a root view controller at the end of application launch”。意思是window需要一个rootViewController,你也许会说,我已经在storyBoard中加好了啊,不就是ViewController么?!是这样的,但是你没有将ViewController的View加进来啊。
另外一点很重要,你不能再像代码方式实现的那样,自己初始化一个window了,因为这个window在storyBoard中已经有了。如果你自己再初始化一个,那么rootViewController的View会被你自己的window挡住。所以,下面这一句应该注释掉:
//self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
同时,添加rootViewController的view到delegate的window:
ViewController *vc=[ViewController alloc] init];
[ self.window addSubview:vc.view];
return Yes;
总结:
1.通过纯代码方式实现时,需要通过代码指定应用Delegate的self.window和self.window.rootViewController,window和rootViewController都需要自已来定义、分配空间、初始化,在没有使用ARC的情况下,还需要控制内存回收。
2.storyBoard实现时,注释掉window的初始化过程。将rootViewController(storyBoard中指定的)的view add到window中。
3.不要即在storyBoard中添加了UINavigationController又在delegate中实现相应的代码,切记。这样的后果是,storyBoard中设置的所有VC会被编译器忽视。