首页 > 解决方案 > 如何调查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的效果。我得到的结果和以前一样。这表明没有强有力的参考。参考这个例子(第二个问题),我们如何确定强保留周期的存在?

在此处输入图像描述

标签: iosswiftmemory-leaksinstrumentsretain-cycle

解决方案


像屏幕截图一样转到Edit Scheme -> Run -> Diagnostics 现在打勾。完成后,重建并运行 . 现在打开,您将在发生内存泄漏的类列表上看到紫色图标。看到这个截图内存泄漏的示例 Repo 是Swift Memory Leak Demo这是内存泄漏的视图,带有附加的 repo 的真实示例您可以在您的项目中按照相同的过程来识别内存泄漏Malloc stack内存调试配置Debug memory graph内存调试图有内存泄漏的真实示例图片


推荐阅读