iOS 開發遵循 MVC 模型,也就是「模型—視圖—控制器」三層結構。
視圖是呈現給使用者看的介面;模型是 App 管理的資料,也常被稱為 App 的引擎;控制器則是串起模型與視圖的橋樑。而在建立與視圖搭配的 ViewController 時,最常見的疑問就是:要不要帶 nib 檔?兩者有什麼不同?
標頭檔:
#import <UIKit/UIKit.h> #import "RootViewController.h" #import "ZYRootViewController.h" @interface ZYAppDelegate : UIResponder <UIApplicationDelegate> @property (strong, nonatomic) UIWindow *window; //@property (strong, nonatomic) RootViewController *rootViewController; @property (strong, nonatomic) ZYRootViewController *rootViewController; @end
實作檔:
@synthesize window = _window;
@synthesize rootViewController;
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// 去掉背景色方便顯示 rootView
// self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
// 無 nib 檔方式
// self.rootViewController = [[RootViewController alloc] initWithNibName:nil bundle:NULL];
// 有 nib 檔方式
self.rootViewController = [[ZYRootViewController alloc] initWithNibName:@"ZYRootViewController" bundle:NULL];
[self.window addSubview:self.rootViewController.view];
return YES;
}
關鍵就在 initWithNibName:bundle: 的第一個參數。
傳入 nil,代表這個控制器沒有對應的 xib/nib 檔,它的 view 必須由你在 loadView 或 viewDidLoad 中用程式碼自行組裝出來。適合版面由程式動態生成、需要高度客製或重用的情境。
傳入字串(例如 @"ZYRootViewController"),系統會去找同名稱的 nib 檔,把裡面預先拉好的視圖物件反序列化並載入。適合版面相對固定、用 Interface Builder 拖拉更快,或需要讓設計師參與的情境。
運行結果:

實務上兩種方式常常混用:整體骨架用程式碼控制,個別複雜的 cell 或自訂 view 則用 xib。選用的標準不是哪個比較好,而是哪個在這個專案裡更好維護。