LoginSignup
8
8

More than 5 years have passed since last update.

UIViewControllerのサブクラスでの初期化定義

Posted at

UIViewControllerをプログラムで作成する場合の初期化(init)の定義方法のまとめです。

新規作成のViewControllerにinitがない

例えば新規「Single View App」を作るとViewController.swiftが作られます。
このファイルにはinitのコードはありません。viewDidLoadなど一部のコードがあるだけです。
「initは定義する必要なし?」かなと思いましたが、親クラスのinitを実行しているようです。

このViewControllerはデフォルトでMain.storyboardに関連づけられているのでこれで問題ありません。

自作のUIViewControllerをプログラムで生成する場合

UIViewControllerのinitを利用する場合は、以下のようになると思います。

let vc = CustomViewController(nibName: nil, bundle: nil)

nil渡すのめんどくさいので、引数なしのinitを定義しますが、初期化方法を理解していないと意外とはまります。

例えば以下のコードを追加するとエラーです。

/// エラーです!
init() {
   // 処理省略
}

サブクラスでinitを定義するときには、必ずrequiredメソッドを実装する必要があります。

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

よく見る奴ですね。ただし、requiredを使わないパターンもあります。それが"convenience init"です。

convenience init() {
   self.init(nibName: nil, bundle: nil)        
}

"convenience init"は初期化っぽく見えますが、初期化処理をラッピングして利用する方法のようです。initとは違います。そのためletなどの初期化はconvenienceの中ではエラーになります。

まとめ

独自のinitを定義する場合はサブクラスでもrequiredも必要になる。convenienceはinitとは違うのでプロパティの初期化はできないようです。

8
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
8