initとinitWithNibNameの関係

自分自身のxibファイルを作ったときinitを呼び出すとxibファイルの中身が見れた

ファイル構成
  • HogeViewController.h
  • HogeViewController.m
  • HogeViewController.xib
ソース
[HogeViewController alloc init]
結果

xibファイルが表示される。

HogeViewControllerとFooViewControllerで同じデザインと発覚したので、親クラスPiyoViewControllerを作った

ファイル構成
  • HogeViewController.h
  • HogeViewController.m
  • FooViewController.h
  • FooViewController.m
  • PiyoViewController.h
  • PiyoViewController.m
  • PiyoViewController.xib

親のデザインを使うのでxibを持っているのは、PiyoViewControllerのみ。

ソース
[HogeViewController alloc init]
結果

真っ黒い画面

解決方法

initをオーバーライドしよう

HogeViewControllerクラス
- (id)init
{
    self = [super initWithNibName:@"PiyoViewController" bundle:nil];

    if (self) {
    }
    
    return self;
}
実行

親のクラス(親のxib)が見れた

めでたしめでたし

ちゃんと 読み込みたいxibを指定しようねってこと。
でも待てよ、なんで子クラスだけのときは、ちゃんと見れたの?

initとinitWithNibNameの関係がきになる

initの中でinitWithNibName呼ばれてるんじゃないかな?

以下のソースで試してみよう。


HogeViewControllerクラス

- (id)init
{
    self = [super init];
    NSLog(@"1");
    
    if (self) {
        
    }
    
    return self;
}


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    NSLog(@"2");
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
[HogeViewController alloc] init]
結果
2
1

まとめ

ソースより initメッソドは内部的に
initWithNibNameメソッドを読んでいるように思える。


initWithNibNameはnibNameOrNilが省略された場合


referenceより引用

        • -

If you use a nib file to store your view controller’s view, it is recommended that you specify that nib file explicitly when initializing your view controller. However, if you do not specify a nib name, and do not override the loadView method in your custom subclass, the view controller searches for a nib file using other means. Specifically, it looks for a nib file with an appropriate name (without the .nib extension) and loads that nib file whenever its view is requested. Specifically, it looks (in order) for a nib file with one of the following names:

If the view controller class name ends with the word “Controller”, as in MyViewController, it looks for a nib file whose name matches the class name without the word “Controller”, as in MyView.nib.
It looks for a nib file whose name matches the name of the view controller class. For example, if the class name is MyViewController, it looks for a MyViewController.nib file.

        • -


のようなルールで.nibが決定されるようであるが、
子クラスでinitした場合つまり

[HogeViewController alloc] init]

した場合、@"HogeViewController"が補われると思われるのだが、
親クラスを作った場合は親クラスの名前(今回は@"PiyoViewController")で補って欲しいわけだが、
ルール上 @"HogeViewController"が補われてしまうので、自分で明示的にinitWithNibName呼ばないと駄目だと推測した。