swift循环引用测试

我们都知道oc在使用block不当的时候会造成循环引用,那么swift会不会造成这种情况呢,我做了一下验证。

第一步构建视图: nav ->ViewControllerA -> ViewControllerB

这样从ViewControllerB 回退  ViewControllerA时,ViewControllerB的实例会被销毁掉。

在ViewControllerB 插入如下代码:

 deinit {
        // 执行析构过程
        print("ViewControllerB is deinit")
    }

实验结果:ViewControllerB is deinit,这说明 ViewControllerB 被顺利销毁掉了。

第二步:ViewControllerB 建立一个contentView,contentView 含有一个闭包,如下:

class UIViewB: UIView {

    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */
    
    var test: (() -> ())?
    
    deinit {
        // 执行析构过程
        print("UIViewB is deinit")
    }

}

ViewControllerB:

   override func viewDidLoad() {
        super.viewDidLoad()

        let contentView = UIViewB(frame: CGRect(x: 0, y: 100,  60, height: 60))
        contentView.backgroundColor = UIColor.white
        view.addSubview(contentView)
        contentView.test = { print(self)}
        // Do any additional setup after loading the view.
    }

这样就形成 ViewControllerB 和  UIViewB 相互持有的情况,再运行一下,结果两个的析构函数都没有运行,说明造成循环引用了,内存泄漏了。

解决方案如下:

        contentView.test = { print(self)}
        contentView.test = {[weak self] in print(self)}

将闭包中的self改成若引用 则可避免循环引用。

完整代码链接:https://github.com/a5978445/swift-

原文地址:https://www.cnblogs.com/TengSys/p/6496699.html