【问题标题】:deinit() ceases to call when this code line of code executes当这行代码执行时 deinit() 停止调用
【发布时间】:2021-07-13 03:31:14
【问题描述】:

最近我一直在查看我的代码,发现在我的一个视图控制器中,没有调用 deinit()。

注释掉这一行后,deinit调用成功:

  NotificationCenter.default.addObserver(forName: .UIKeyboardWillShow, object: nil, queue: nil)
        { notification in self.keyboardWillShow(notification: notification) }

我知道您需要删除观察者,但如果我替换

self.keyboardWillShow(notification: notification)

print("hello world")

deinit() 调用成功。

我的本​​地函数“keyboardWillShow”中的代码被注释掉了,但是函数签名是

func keyboardWillShow(notification: Notification)

关于如何改进此代码以不保留引用并正确点击 deinit()/

的任何建议

谢谢!!

【问题讨论】:

    标签: ios swift memory manual-retain-release


    【解决方案1】:

    您的闭包正在捕获对self 的强引用,这会阻止您的对象被释放;你有一个保留周期。当你不在闭包中引用self 时,你就避免了这个循环,这就是为什么当你只有print 语句时你的视图控制器被释放。

    您可以在闭包中使用[weak self] 来防止这种情况;然后你需要在使用它之前在闭包中解开 self。

    NotificationCenter.default.addObserver(forName: .UIKeyboardWillShow, object: nil, queue: nil) 
    { [weak self] notification in 
        self?.keyboardWillShow(notification: notification)
    }
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-08
      相关资源
      最近更新 更多