对比Xcode Debug Memory Graph和FBMemoryProfiler

内存泄露一直是一个头疼的问题,需要工程化的阶段来解决。之前在每个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

猜你喜欢

转载自yq.aliyun.com/articles/624116
今日推荐