iOS 图表如何处理空数据集

iOS charts what to do with empty dataset

我在我的项目中使用图表。但是,我现在 运行 遇到一个问题,如果数据集为空,当我看到调试区域时,我将全部报告错误。

现在我正在尝试找到一种解决方案,以便能够在数据集为空时停止创建图表。

我收到 25 次错误消息:

[32865:1852701] [Unknown process name] CGAffineTransformInvert: singular matrix.

目前我有这个解决方案,但我不知道是否有更好的解决方案。

var gewichtenHond: [GewichtHond] = [] {
    didSet {
        if self.gewichtenHond.count == 0 {
            self.lineChartView.noDataText = "Geen data beschikbaar om een grafiek te tekenen."
        } else {
            grafiekData(animatieSnelheid: 1.0, typeAnimatie: .easeInBounce)
        }
        tableView.reloadData()
    }
}

override func viewDidLoad() {
    super.viewDidLoad()
}

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    getGewichtenHond()
}

func getGewichtenHond() {
    let appDelegate = UIApplication.shared.delegate as? AppDelegate
    let context = appDelegate?.persistentContainer.viewContext

    let hondFetch = NSFetchRequest<NSFetchRequestResult>(entityName: "Hond")
    hondFetch.predicate = NSPredicate(format: "hondId = %@", hondId)

    let honden = try! context?.fetch(hondFetch)
    let hond: Hond = honden?.first as! Hond
    self.gewichtenHond = hond.gewichten?.allObjects as! [GewichtHond]
}

for now I have this solution but I don't know if there is a better one.

从你的代码可以看出,你每次打开场景都在尝试获取数据,如果是的话试试这个方法

class UIViewController : UIViewController{

var gewichtenHond: [GewichtHond] = [] {
    didSet {
        grafiekData(animatieSnelheid: 1.0, typeAnimatie: .easeInBounce)
        tableView.reloadData()
    }

}

override func viewDidLoad() {
    super.viewDidLoad()
    let appDelegate = UIApplication.shared.delegate as? AppDelegate
    let context = appDelegate?.persistentContainer.viewContext
}

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    self.lineChartView.noDataText = "Geen data beschikbaar om een grafiek te tekenen."
    getGewichtenHond()

}
func getGewichtenHond() {
    let hondFetch = NSFetchRequest<NSFetchRequestResult>(entityName: "Hond")
    hondFetch.predicate = NSPredicate(format: "hondId = %@", hondId)

    let honden = try! context?.fetch(hondFetch)
    let hond: Hond = honden?.first as! Hond
    self.gewichtenHond = hond.gewichten?.allObjects as! [GewichtHond]

}

}

如果你只是想在打开场景时只获取一次,我建议你移动 这两行

self.lineChartView.noDataText = "Geen data beschikbaar om een grafiek te tekenen."
    getGewichtenHond() 

viewDidLoad 方法中,因为 viewWillAppear 会在您每次离开场景并返回时触发