Search code examples
iosswiftuiviewinitializing

What happens when I am initializing my UIView in subclasses?


A.swift

class A: UIView {

    override init() {
        super.init()
        println("init A")
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        println("initFrame A")
    }
}

B.swift

class B: A {

    override init() {
        super.init()
        //P1
        println("init B")
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        println("initFrame B")
    }
}

Then I call it B():

I have an output:

initFrame A
initFrame B
init A
init B

I try to determine what? is called and when?... after B(). I wish to understand it completely.

  1. init() in A
  2. super.init() in init() in A
  3. init() in B
  4. super.init() in init() in B
  5. init() in UIView
  6. super.init() in init() in UIView

now we are in P1 point, right?

  1. init() calls init(frame:) in B with CGRectZero
  2. super.init(frame:) in init(frame:) in B
  3. init(frame:) in A
  4. super.init(frame:) in init(frame:) in A
  5. init(frame:) in UIView
  6. super.init(frame:) in init(frame:) in UIView

now we are getting back

  1. called the rest of init(frame:) in UIView
  2. called the rest of init(frame:) in A --> initFrame A
  3. called the rest of init(frame:) in B --> initFrame B

The question is what is happening now? Where we are now? (inside init() in UIView?) Where are printed the lines with init A and init B?

Thanks for help.


Solution

    1. B() calls B's init()
    2. This results in a call to init() defined in B's superclass A (due to super.init() in B's init())
    3. This, in turn, results in a call to init() defined in A's superclass UIView (due to super.init() in A's init())
    4. UIView's init() invokes init(frame: CGRectZero) on the current instance
    5. Since the current instance is of class B, and class B overrides init(frame: CGRect), B's own implementation of the method is invoked
    6. This results in a call to A's init(frame: CGRectZero) (due to super.init(frame: frame) in B's init(frame: CGRect))
    7. As a consequence, UIView's init(frame: CGRectZero) is called (due to super.init(frame: frame) in A's own implementation)
    8. This concludes the chain of calls
    9. Great, now we're going back down to A's init(frame: CGRectZero) (point 6 in the list), which prints initFrame A
    10. Back down to B's init(frame: CGRectZero) (point 5), which prints initFrame B
    11. Now back again to UIView's init() (point 3), which doesn't print anything
    12. We return to A's init() (point 2), that prints initA
    13. Finally, we finish our trip at B's init() (point 1), which prints initB, that you marked with P1

    Please let me know if the steps are clear, of if I need to add more details to improve the explanation: I know it's a bit convoluted.