Fog*_*ter 7 memory-leaks ios swift
我花了一整天的时间来追逐来自某个地方的内存泄漏...而我刚刚找到它.
除此之外,我不知道它为什么会破碎.我不知道为什么我的改变已经解决了.
因此,我创建了一个最小的破坏性示例,以便在此处尝试清除为什么会发生这种情况.
故事板非常简单.它包含了UINavigationController一个rootViewController类型的ViewController,这推到AnotherViewController.
我有一个协议定义...
protocol MyProtocol {}
Run Code Online (Sandbox Code Playgroud)
并AnotherViewController符合它......
class AnotherViewcontroller: UIViewController, MyProtocol {
deinit {
print(#function, "Another View Controller")
}
}
Run Code Online (Sandbox Code Playgroud)
我添加了deinit方法来显示正在发生的事情.
该ViewController代码稍微有趣,但也很简单...
class ViewController: UIViewController, UINavigationControllerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
navigationController?.delegate = self
}
func navigationController(_ navigationController: UINavigationController,
animationControllerFor operation: UINavigationControllerOperation,
from fromVC: UIViewController,
to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
switch (fromVC, toVC) {
case (is MyProtocol, is MyProtocol):
print(" NOOOOOO!")
return nil
default:
print(" Yippee!")
return nil
}
}
}
Run Code Online (Sandbox Code Playgroud)
ViewController 不符合MyProtocol.
它成为了navigationController代表.
并实现了返回动画转换控制器的功能.但在这种情况下,我只是return nil因为我不想改变动画.
这里没有什么复杂的事情发生.
当我运行应用程序时,它会打开Push屏幕中央的按钮.我点按Push按钮然后转换到AnotherViewController.在控制台我有 Yippee!.
当我现在点击后退按钮时,我 Yippee!再次进入控制台并弹回第一个视图控制器.
注意:它永远不会显示红苹果.它永远不会进入那种情况.它所做的只是检查两者
fromVC并toVC符合MyProtocol.
除此之外,AnotherViewController还没有解除分配.内存泄漏在这里.如果我运行内存图调试器,我可以看到它仍在内存中.
所以,我找到了两种可能的方法来解决这个问题......做其中任何一个都会解决它.
第一种方式......添加class到协议.通过将协议定义更改为protocol MyProtocol: class {}它可以解决问题.它仍将显示绿色苹果,但现在它将正常解除分配.
第二种方式......不要问视图控制器是否符合协议.如果我case (is MyProtocol, is MyProtocol)从交换机中删除并保留默认值,那么它现在将正确释放视图控制器并修复内存泄漏.它不会改变行为.它仍然显示青苹果.但现在有效.
如果我单独留下所有代码并使其ViewController符合,MyProtocol那么AnotherViewController将被正常释放(除了它现在显示红苹果).
那么......为什么会这样呢?它对类协议位有意义,因为它现在知道它是一个引用类型......但仍然不确定为什么询问它是否符合导致泄漏?
而且......为什么要问它是否符合非类协议导致它泄漏?
如果你删除switch并只是使用an if来检查它们是否都符合协议,if toVC is MyProtocol那么它仍然可以解除分配.似乎只有它在交换机中.
如果我删除协议的检查,而是检查类... case (is AnotherViewController, is AnotherViewController):那么这也不会影响它.它仍然正常解除分配.
如果有人能对此有所了解,我很想知道这里发生了什么.
谢谢
| 归档时间: |
|
| 查看次数: |
352 次 |
| 最近记录: |