不知道是不是有人和我一樣,有著不好的習慣,寫著寫著代碼,又覺得用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會被編譯器忽視。