What exactly is init coder aDecoder?

后端 未结 2 524
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-04 07:03

I\'m learning iOS development from an online course and everytime I make a custom view (custom table view cell, collection view cell, etc) the instructor always implements t

2条回答
  •  再見小時候
    2020-12-04 07:33

    The requirement to implement that initializer is a consequence of two things:

    1. The Liskov substitution principle. If S is a subclass of T (e.g. MyViewController is a subclass of ViewController), then S objects (instances of MyViewController) must be able to be substituted in where T objects (instances of ViewController) are expected.

    2. Initializers are not inherited in Swift if any initializers are explicitly defined in the subclass. If one initializer is explicitly provided, then all others must be explicitly provided (which can then just call super.init(...)). See this question for rationale. It's in Java, but still applies.

    By point 1, everything the original ViewController can do, the MyViewController subclass should be able to do. One such thing is to be able to be initialized from a given NSCoder. By point 2, your MyViewController subclass doesn't automatically inherit this ability. Thus, you must manually supply the initializer that fulfills this requirement. In this case, you just need to delegate up to the superclass, to have it do what it would usually do.

提交回复
热议问题