我手动创建了一个内存泄漏,但调试内存图无法检测到它。
这只发生在控制器上,而不是在通用对象类型上。
有人知道为什么吗?
这是我使用的代码
import UIKit
class ViewController: UIViewController {
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
present(Demo(), animated: true, completion: nil)
}
}
class Demo : UIViewController {
var obj:Demo?
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .systemTeal
obj = self
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
dismiss(animated: true, completion: nil)
}
}
看起来UIViewController开始观察UIApplicationSuspendedNotification。
开始观察有两种方法:
addObserver(_:选择器:名称:对象:)
addObserver (forName:对象:队列:使用:)
两者都保持弱引用到我们的Demo视图控制器。
演示vc中addObserver通过第一种方法。看起来苹果没有考虑到内存泄漏对象的观察NotificationCenter。
我通过下面的调试步骤得到这个信息:
1。
在打开调试器启用后,启用Malloc堆栈日志记录在项目方案中,我发现__NSObservers引用。
2。
然后我看Backtrace,发现有一个调用[NSNotificationCenter addObserver:selector:name:object:]。
我用方法名[NSNotificationCenter addObserver:selector:name:object:]添加了符号断点,并打印所有参数$arg1 $arg2 $arg3 $arg4 $arg5 $arg6,并找到观察的名称。
使用地址的NotificationCenter和我的ViewController的地址,我通过[notificationcenteraddress removeObserver: viewcontrollerress]删除观察,并重新打开内存调试器。调试器将viewController视为内存泄漏。(在截图中有12个实例,因为我在背景上录制了多次)。