iOS: How to check if UIViewControllers are unloading? (Swift)

不羁的心 提交于 2019-12-03 02:55:44

You have a view with a delegate property that references back to the view controller. This will result in a strong reference cycle (previously known as a retain cycle) because the view controller is maintaining a strong reference to its top level view which is, in turn, maintaining a strong reference back to the view controller.

In the Resolving Strong Reference Cycles Between Class Instances section of The Swift Programming Language: Automatic Reference Counting, Apple describes how to address this:

Swift provides two ways to resolve strong reference cycles when you work with properties of class type: weak references and unowned references.

Weak and unowned references enable one instance in a reference cycle to refer to the other instance without keeping a strong hold on it. The instances can then refer to each other without creating a strong reference cycle.

Use a weak reference whenever it is valid for that reference to become nil at some point during its lifetime. Conversely, use an unowned reference when you know that the reference will never be nil once it has been set during initialization.

Thus, you can resolve your strong reference cycle by defining the delegate to be weak:

weak var delegate: ManageViewDelegate? 

For that to work, you have to specify your protocol to be a class protocol:

protocol ManageViewDelegate: class {
    // your protocol here
}

That will resolve the strong reference cycle and eliminates the need to manually nil the delegate in order to resolve the strong reference cycle.

Also if you use blocks you need to add [weak self], otherwise,the view wouldn't be destroyed

 setupObserve(postID) {
        [weak self] chatRequest in
    self?.update()
 }

The deinit function should work out

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!