对比Xcode Debug Memory Graph和FBMemoryProfiler

简介: 内存泄露一直是一个头疼的问题,需要工程化的阶段来解决。之前在每个VC的deinit打印一些日志,因为日志太多,看到泄露信息并不容易。跑Instruments成本也比较高,很多时候并不想去跑。所以对比了一下Memory Debug Graph和[FBMemoryProfiler](https://github.com/facebook/FBMemoryProfiler)。 ### Memory

内存泄露一直是一个头疼的问题,需要工程化的阶段来解决。之前在每个VC的deinit打印一些日志,因为日志太多,看到泄露信息并不容易。跑Instruments成本也比较高,很多时候并不想去跑。所以对比了一下Memory Debug Graph和FBMemoryProfiler

Memory Debug Graph

Memory Debug Graph是Xcode8新增的feature,跟Xcode无缝融合,用起来比较方便,模拟器开发测试一段时间之后,不妨看一下Xcode Runtime issue,是否有警告。

screenshot.png

如果想要看到右侧的内存申请时的堆栈,需要在Scheme里面勾选上Malloc Stack

screenshot.png

打开Malloc Stack选项之后,会在沙箱的/tmp/目录下会产生巨大的日志文件,平时最好把它关掉。

-rw-r--r-- 1 henshao staff 30M 12 26 10:31 stack-logs.3214.102414000.CloudConsoleApp.SrkAcU.index

Memory Debug Graph的缺点是只有图形化界面,没有SDK,这样的话只能连着Xcode操作。如果有SDK的话,可以在代码里面检测内存警告,发现有内存泄露上传日志,弹个框什么的。

FBMemoryProfiler

FBMemoryProfiler是Facebook开源的一个工具,有SDK可以用,接入是非常之方便的。但是目前来看,对Swift并不支持,所以用Swift的同学就不要使用这个工具了。

screenshot.png

测试代码

代码中构造了两种内存泄露,一种是简单的循环引用,另外一种是block capture。

import UIKit
import FBMemoryProfiler

class RetainCycleLoggerPlugin : NSObject, FBMemoryProfilerPluggable {

    func memoryProfilerDidFindRetainCycles(_ retainCycles: Set<AnyHashable>) {
        print("==FBMemoryProfiler: \(retainCycles)")
    }
}

class Foo {
    var vc : MemoryLeakViewController?
}

typealias BarBlock = ()->Void

class MemoryLeakViewController : UIViewController {

    var foo : Foo?
    var barBlock : BarBlock?

    override func viewDidLoad() {
        super.viewDidLoad()

        self.title = "Memory Leak VC"
        self.view.backgroundColor = UIColor.blue

//        self.foo = Foo()
//        self.foo?.vc = self

        self.barBlock = {
            self.view.backgroundColor = UIColor.white
        }

        self.barBlock?()
    }
}

class ViewController: UIViewController {

    let memoryProfiler = FBMemoryProfiler(plugins: [RetainCycleLoggerPlugin()], retainCycleDetectorConfiguration: nil)

    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "Root VC"
        self.view.backgroundColor = UIColor.white

        memoryProfiler.enable()
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)

        let memoryLeakVC = MemoryLeakViewController()
        self.navigationController?.pushViewController(memoryLeakVC, animated: true)
    }
}

对比结果

Memory Debug Graph探测是非常精准的,两种内存泄露都发现了。

screenshot.png

screenshot.png

FBMemoryProfiler什么都没有发现。

screenshot.png

==FBMemoryProfiler: []
==FBMemoryProfiler: []
==FBMemoryProfiler: []
==FBMemoryProfiler: [AnyHashable(<__NSArrayM 0x600000244410>(
-> target -> FBMemoryProfilerViewController ,
-> _timer -> __NSCFTimer 
)
)]
==FBMemoryProfiler: [AnyHashable(<__NSArrayM 0x600000246360>(
-> (null) ,
-> (null) 
)
)]
==FBMemoryProfiler: []
==FBMemoryProfiler: []
==FBMemoryProfiler: []
==FBMemoryProfiler: []
==FBMemoryProfiler: [AnyHashable(<__NSArrayM 0x60000024c960>(
-> target -> FBMemoryProfilerViewController ,
-> _timer -> __NSCFTimer 
)
)]
==FBMemoryProfiler: [AnyHashable(<__NSArrayM 0x600000254700>(
-> target -> FBMemoryProfilerViewController ,
-> _timer -> __NSCFTimer 
)
)]
==FBMemoryProfiler: []
==FBMemoryProfiler: []
==FBMemoryProfiler: []

实战情况

我们使用Debug Memory Graph还真发现了一个二方模块的循环引用。这也说明了添加特定前缀的重要性。比如我们的前缀是ALY,我在模拟器里面使用一阵子之后,跑去Debug Memory Graph的runtime issue搜索ALY,就可以知道我们自己代码的内存泄露啦。

graph.png

泄露的代码如下所示。presenter的completion block capture了VC,而VC的eventHandler又拿住了presenter,导致循环引用。只要在presenter的completion block对VC做一个weak即可解决问题。

ALYPatternLockPresenter *presenter = [[ALYPatternLockPresenter alloc] init];
ALYPatternLockViewController *vc = [[ALYPatternLockViewController alloc] initWithNibName:@"ALYPatternLockViewController" bundle:[NSBundle mainBundle]];
if ([self patternLockWasSet]) {
    [vc setActionPrompt:title];
    // 如果强制验证,无法取消,隐藏取消按钮
    [vc setCancelButtonHidden:force];
    presenter.userInterface = vc;
    presenter.mode = ALYPatternLockValidateMode;
    WEAK_SELF
    presenter.completion = ^(BOOL result, NSError *error) {
        STRONG_SELF
        if (result) {
            [self dismissViewControllerAboveAWindow:vc animated:animated completion:^{
                completion(YES, nil);
            }];
        } else {
            [self dismissViewControllerAboveAWindow:vc animated:animated completion:^{
                completion(NO, error);
                if (error.code == ALYPatternLockErrorTooManyAttempts
                    || error.code == ALYPatternLockErrorForget) {
                    if (self.callback != nil) {
                        self.callback();
                    }
                }
            }];
        }
    };
    vc.eventHandler = presenter;
    vc.touchIDEnabled = [[ALYPatternLockService sharedInstance] touchIDEnabled];
    [vc setActionPrompt:title];
    [self presentViewControllerAboveAWindow:vc animated:animated];

参考资料

  1. iOS——抢鲜来体验一下FBMemoryProfiler
  2. Visual Debugging with Xcode
相关实践学习
日志服务之使用Nginx模式采集日志
本文介绍如何通过日志服务控制台创建Nginx模式的Logtail配置快速采集Nginx日志并进行多维度分析。
相关文章
|
NoSQL iOS开发 C++
Xcode Debug 大全
BUG,简单来说就是程序运行结果与预期的不同,下面来说说Xcode中的DEBUG方法
331 0
|
10月前
|
iOS开发
Xcode如何编译Debug版和Release版​
Xcode如何编译Debug版和Release版​
|
11月前
|
iOS开发
Xcode如何编译Debug版和Release版​
Xcode如何编译Debug版和Release版
|
iOS开发 开发者 程序员
XCode Debug
引言: 程序调试技巧在开发过程中起着举足轻重的地位,熟练的使用可以加快我们捕捉问题的速度. 毕竟BUG这个词是我们程序员一直要伴随的字眼,最关键的,人不是计算机,总有那么一点点小细节容易在我们慎密的思绪中偷偷溜走,从而导致一个BUG的出现.
1445 0
|
iOS开发 编译器
xcode反汇编调试iOS模拟器程序(七)Debug与Release的区别
首先自己写一段代码,加好断点,分别在Build Configuration为Debug和Release下运行,查看反汇编 - (void)test { UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(10.
893 0
|
2月前
|
Linux 数据安全/隐私保护 iOS开发
如何使用 Xcode 打包导出 IPA 文件并进行 iOS 应用内测,无需支付苹果开发者账号费用?
如何使用 Xcode 打包导出 IPA 文件并进行 iOS 应用内测,无需支付苹果开发者账号费用?