LoginSignup
4
1

More than 3 years have passed since last update.

iOS-Chartsの注意点

Posted at

環境

Xcode 10.2.1, Swift5
danielgindi/Charts: Beautiful charts for iOS/tvOS/OSX! The Apple side of the crossplatform MPAndroidChart.
version 3.3.0

インストール方法は、
ios-chartsに関する記事 - Qiita
の他の記事読めば出てくるので割愛。

個人的に躓いた点

IAxisValueFormatterのdelegateをViewControllerにすると、deinitされなくなるので、
IAxisValueFormatterを継承した子クラスを作成する

解放されるケース

CombinedChartViewController.swift
chartView.xAxis.valueFormatter = XAxisValueFormatter()

class XAxisValueFormatter: IAxisValueFormatter {
    let months = ["Jan", "Feb", "Mar",
                  "Apr", "May", "Jun",
                  "Jul", "Aug", "Sep",
                  "Oct", "Nov", "Dec"]

    // X軸のラベルを設定する
    func stringForValue(_ value: Double, axis: AxisBase?) -> String {
        return months[Int(value) % months.count]
    }
}

解放されなくなるケース(DemoのCombinedChartViewController)

CombinedChartViewController.swift
extension CombinedChartViewController: IAxisValueFormatter {
    func stringForValue(_ value: Double, axis: AxisBase?) -> String {
        return months[Int(value) % months.count]
    }
}

なぜVCだと解放(リーク)されないのか

・パット見delegate protocolのように定義されているかつ、
Demoや他の記事でも、チャートを表示するViewControllerのextensionでIAxisValueFormatterを実装しているが、
実はライブラリ内で弱参照でなく強参照している為、解放されなくなる。
・Issueとして上がってるが、それなりの修正が必要なようで保留になっている。
Should valueFormatter property use weak modifier? · Issue #1873 · danielgindi/Charts
・強参照しているのが原因なので、
viewWillDisapperでchartView.xAxis.valueFormatter = nilにしても解放される。

4
1
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
4
1