對比XcodeDebugMemoryGraph和FBMemoryProfiler

阿呆少爺發表於2018-08-10

記憶體洩露一直是一個頭疼的問題,需要工程化的階段來解決。之前在每個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


相關文章