Deinit not called on a UIViewController, but Dealloc is

前端 未结 2 2001
生来不讨喜
生来不讨喜 2020-12-31 02:02

It seems like the Swift equivalent of dealloc is deinit. However, when you attempt to define the method on a UIViewController, it doesn\'t behave as you would expect...

2条回答
  •  隐瞒了意图╮
    2020-12-31 02:51

    TLDR:

    Breakpoints will only work in deinit if there is an executable line of code ahead of them.

    • If you place a breakpoint on a line of executable code, then it will work.
    • The executable line of code must belong to the deinit method.

    Thanks to Adam for pointing me in the right direction. I didn't do extensive tests, but it looks like breakpoints behave differently in deinit than everywhere else in your code.

    I will show you several examples where I added a breakpoint on each line number. Those that will work (e.g. pause execution or perform their action such as logging a message) will be indicated via the ➤ symbol.

    Normally breakpoints are hit liberally, even if a method does nothing:

    ➤ 1
    ➤ 2  func doNothing() {
    ➤ 3 
    ➤ 4  }
      5
    

    However, in a blank deinit method, NO breakpoints will ever get hit:

      1
      2  deinit {
      3 
      4  }
      5
    

    By adding more lines of code, we can see that it depends on if there is an executable line of code following the breakpoint:

    ➤ 1 
    ➤ 2  deinit {
    ➤ 3      //
    ➤ 4      doNothing()
    ➤ 5      //
    ➤ 6      foo = "abc"
      7      //
      8  }
      9
    

    In particular, play close attention to lines 7 and 8, since this differs significantly from how doNothing() behaved!

    If you got used to this behavior of how the breakpoint on line 4 worked in doNothing(), you may incorrectly deduce that your code is not executing if you only had a breakpoint on line 5 (or even 4) in this example:

    ➤ 1  
    ➤ 2  deinit {
    ➤ 3      number++
      4  //    incrementNumber()
      5  }
      6
    

    Note: for breakpoints that pause execution on the same line, they are hit in the order that they were created. To test their order, I set a breakpoint to Log Message and Automatically continue after evaluating actions.

    Note: In my testing there was also another potential pitfall that might get you: If you use print("test"), it will pop up the Debug Area to show you the message (the message appears in bold). However, if you add a breakpoint and tell it to Log Message, it will log it in regular text and not pop open the Debug Area. You have to manually open up the Debug Area to see the output.

    Note: This was all tested in Xcode 7.1.1

提交回复
热议问题