ios - 如何调查ios中的内存泄漏?
问题描述
我创建了一个简单的流程来测试 ios 应用程序中的内存。我在导航堆栈中有两个视图控制器。我在第一个视图控制器中显示一个警报,以允许用户移动到下一个。以下是我正在使用的代码。
class ViewController: UIViewController {
@IBOutlet weak var labelInfo: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func showNextScreen(_ sender: Any) {
let alert = UIAlertController(title: "Alert", message: "Go to next screen?", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Yes", style: .default, handler: { [unowned self] (action) in
self.performSegue(withIdentifier: "showNextScreen", sender: nil)
}))
alert.addAction(UIAlertAction(title: "No", style: .default, handler: { [unowned self] (action) in
self.labelInfo.text = "You did not move to next screen"
alert.dismiss(animated: true, completion: nil)
}))
self.present(alert, animated: true, completion: nil)
}
}
在浏览了提到不应该有强引用循环的资源后,我在代码中使用了unowned self。检查Instruments中的泄漏,我得到了下图。
该图显示没有泄漏,如绿色刻度线所示。然而,当我在两个视图控制器之间来回移动时,内存使用图正在增加。什么可能导致内存使用量增加(第一个问题)?
接下来,我还检查了将unowned self替换为self的效果。我得到的结果和以前一样。这表明没有强有力的参考。参考这个例子(第二个问题),我们如何确定强保留周期的存在?
解决方案
像屏幕截图一样转到Edit Scheme -> Run -> Diagnostics
现在打勾。完成后,重建并运行 . 现在打开,您将在发生内存泄漏的类列表上看到紫色图标。看到这个截图内存泄漏的示例 Repo 是Swift Memory Leak Demo这是内存泄漏的视图,带有附加的 repo 的真实示例您可以在您的项目中按照相同的过程来识别内存泄漏Malloc stack
Debug memory graph
推荐阅读
- c# - 导航服务参数 (INavigationService)
- javascript - 通过循环内的条件更改附加的 td
- erlang - ETS 表 - 将地图更新为记录
- wpf - 如何向已经使用样式模板的窗口添加其他样式
- sql - 从多个组中选择结果然后按降序对每个组进行排序的存储过程?
- python-3.x - 每当我运行此代码时,我都会收到这种错误
- firebase - Firebase auth uid 不解释实际值
- javascript - 通过 PHP 处理 AJAX 数据数组 - 没有 $_POST 发生?
- c# - 我应该使方法虚拟还是抽象?
- javascript - 为什么不触发回调函数?