2019-01-02 swift 中发生的循环引用
2019-01-02 本文已影响17人
幸福晓杰2016
最近使用xcode工具检查,并没有发现循环引用。
结果最后,同事告诉我写的viewcontroller 没有释放。
我仔细检查代码,发现了一下问题和结论:
第一:swift 框架中 then 方法,传入的block是临时变量,执行完就销毁,是栈block 不存在循环引用。
第二: 被对象拥有的block ,在赋值时,会被系统转换为堆block,那么为了避免内存泄露,这里面只要用了self,或者隐式调用self的一些属性对象时,一定要加上[unowned self]
第三:swift中定义协议时,如果这样写
protocol PenguinDelegate {
func userDidTapThePenguin()
}
class MyViewController: UIViewController {
weak var delegate: PenguinDelegate?
}
weak 属性修饰会报错。
'weak' must not be applied to non-class-bound 'ALMHeaderViewBtnClick'; consider adding a protocol conformance that has a class bound
网上查资料得知,weak与弱引用计数有关,只能修饰对象,不能修饰协议限制的any。
修改如下,让协议继承: NSObjectProtocol 或者class 即可。
参考文章
protocol PenguinDelegate: NSObjectProtocol {
func userDidTapThePenguin()
}
class MyViewController: UIViewController {
weak var delegate: PenguinDelegate?
}
或者
protocol PenguinDelegate: class {
func userDidTapThePenguin()
}
class MyViewController: UIViewController {
weak var delegate: PenguinDelegate?
}
或者同事的方法
@objc protocol PenguinDelegate {
func userDidTapThePenguin()
}
class MyViewController: UIViewController {
weak var delegate: PenguinDelegate?
}