如何将核心数据属性的值放入条形图中(Swift UIKit、Charts、CoreData)?

问题描述 投票:0回答:0

我正在尝试制作一个条形图来显示保存一年的核心数据值(逐月) sample of chart I am trying to achieve (like in the IOS health app)

我建立了一个核心数据模型,实体名称为“ScoreSet”,属性为“createdDate”和“score”(当前保存的值有:createdDate:2023-01-12 20:07:25,score:27 ;创建日期:2023-02-13 25:10:05,得分:45;创建日期:2023-02-14 10:17:01,得分:25;创建日期:2023-03-15 15:00:29,得分: 5)

我放在一起的代码有点工作(但不是真的)它只会将最后的分数结果传送到条形图(所以它会显示最后保存的分数,目前是“5”)。我知道我只列出了 1 个显示在 x 轴上,但我试图弄清楚如何使模型实体的“分数”值成为一个数组或循环。

import UIKit
import Charts
import CoreData

class BarChartViewController: UIViewController, ChartViewDelegate, NSFetchedResultsControllerDelegate {

let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
  
var barChart = BarChartView()
    
var  scoreTotal: Int64 = 0
var  dates = Date()

override func viewDidLoad() {
super.viewDidLoad()

barChart.delegate = self
barChart.frame = CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height)
barChart.center = view.center
        
view.addSubview(barChart)

let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "ScoreSet")

do {
   let results = try context.fetch(fetchRequest)
   let result = results as! [ScoreSet]
                
   for data in result as [NSManagedObject] {
   scoreTotal = data.value(forKey: "score") as! Int64
   dates = data.value(forKey: "createdDate") as! Date
  
    print(dates) // this prints in the output as stated below
    print(scoreTotal) // this prints in the output as stated below

    }

    } catch let error as NSError {
    print("Could not fetch \(error)")
    }

 let set = BarChartDataSet(entries: [
 //with this code it gives only the last score listed in the coredata entity, but what I’d like to get is all the scores fetched along with putting them in the appropriate month
BarChartDataEntry(x: 1, y: Double(scoreTotal))
                  ])

let data = BarChartData(dataSet: set)
        
        barChart.data = data
    }
}

xcode 输出打印结果(从核心数据中获取)确实显示了我想放入图表中的分数数据(最终一年的数据会有更多数据,但目前只有 4 个):

2023-01-12 20:07:25 +0000
27
2023-02-13 25:10:05 +0000
45
2023-02-14 10:17:01 +0000
25
2023-03-15 15:00:29 +0000
5

所以我正在寻找一种方法来获取该数据并将其显示在条形图中。

感谢您的帮助。

arrays swift core-data uikit bar-chart
© www.soinside.com 2019 - 2024. All rights reserved.