LoginSignup
13
9

More than 5 years have passed since last update.

iOSでメモリーリークを簡単に検知できるようにする方法

Last updated at Posted at 2018-12-16

はじめに

  • メモリーリークはアプリの挙動を不安定にする要因となる
  • Xcode の Debug Memory Graphなどを使う方法もあるが毎回調べるのにコストがかかる
  • krzysztofzablocki/LifetimeTrackerを導入することでアプリがメモリーリークをしていることに開発者が気が付きやすくなる

  • 今回はLifetimeTrackerについて詳しくまとめます

LifetimeTrackerとは

Find retain cycles / memory leaks sooner.

  • LifetimeTrackerはメモリーリークをアプリ実行時に把握できるようにするツールです
  • 導入することでアプリ実行時にUI上で確認できるようになります
  • krzysztofzablocki/Sourceryのコントリビュータでもあるkrzysztofzablockiが作者である

環境

Xcode 10.1
Build version 10B61
Apple Swift version 4.2.1 (swiftlang-1000.11.42 clang-1000.11.45.1)
Target: x86_64-apple-darwin18.2.0

導入方法

1. pods or carthageでLifetimeTrackerをインストール

pods

pod 'LifetimeTracker'

carthage

github "krzysztofzablocki/LifetimeTracker"

2.セットアップの処理をAppDelegateに追加

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
     LifetimeTracker.setup(onUpdate: LifetimeTrackerDashboardIntegration(visibility: .alwaysVisible, style: .bar).refreshUI)
     return true
}

3.メモリーリークを調べたいViewControllerに実装を追加

import UIKit
import LifetimeTracker

class ViewController: UIViewController {
    static var lifetimeConfiguration = LifetimeConfiguration(maxCount: 1, groupName: "VC")
    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
        trackLifetime()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        trackLifetime()
    }
}

extension ViewController: LifetimeTrackable {}

実際の画面

  • サンプルコード
  • メモリに保持されているインスタンスの数がメニュー画面で確認できます
  • maxCountを設定することでインスタンスの数がmaxCountを超えた場合メニューに警告として表示される
  • groupNameを指定することでメニューで別のグループとして、まとめて表示されます
  • メニューの出し方も色々と選べるので実装時に邪魔にならないようになっています

参考リンク

13
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
9