Sean's Note: initWithNibName 和 loadNibNamed 方法的區別

2015年2月17日 星期二

initWithNibName 和 loadNibNamed 方法的區別

initWithNibNameloadNibNamed 都可以用來建立 Custom ViewController,
// 延遲載入,用到時才會值
MyViewController *viewController = [[MyViewController alloc] initWithNibName:@"MyViewController" bundle:nil];

MyViewController *viewController = [[[NSBundle mainBundle] loadNibNamed:@"MyViewController" owner:self options:nil] objectAtIndex:0];

但是在 NIB 上的設定會有不同:
initWithNibName 的 XIB 需要在 Placeholders 設置 File's Owner 的 Custom Class,
View Controller 則不須設置 Custom Class。而且拉的元件是 UIView。
反之,用 loadNibNamed 的 XIB 不能在 Placeholders 設置 File's Owner 的 Custom
Class,而 View Controller 則須設置 Custom Class。而且拉的元件是 UIViewController。
若兩者誤用,就會跑出 setValue:forUndefinedKey 的錯誤。

沒有留言:

張貼留言