我从解析后端获取值并使用它们创建数组,但没有任何内容存储在其中。有人可以告诉我我做错了什么吗?行:let dataEntry = ChartDataEntry(value:values [i],xIndex:i)返回" index超出范围"
var fattyArray: [Double] = []
override func viewDidLoad() {
super.viewDidLoad()
let innerQuery = PFUser.query()
innerQuery!.whereKey("objectId", equalTo: "VTieywDsZj")
let query = PFQuery(className: "BodyFat")
query.whereKey("UserID", matchesQuery: innerQuery!)
query.findObjectsInBackgroundWithBlock {
(percentages: [PFObject]?, error: NSError?) -> Void in
if error == nil {
print("Successful, \(percentages!.count) retrieved")
if let percentage = percentages as [PFObject]! {
for percentage in percentages! {
print(percentage["BodyFatPercentage"])
self.fattyArray.append(percentage["BodyFatPercentage"].doubleValue)
print(self.fattyArray)
}
}
} else {
print("\(error?.userInfo)")
}
}
let months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"]
let unitsSold = fattyArray
setChart(months, values: unitsSold)
}
func setChart(dataPoints: [String], values: [Double]) {
var dataEntries: [ChartDataEntry] = []
for i in 0..<dataPoints.count {
let dataEntry = ChartDataEntry(value: values[i], xIndex: i)
dataEntries.append(dataEntry)
}
答案 0 :(得分:1)
这里有两个问题:
一个问题是findObjectsInBackgroundWithBlock
异步运行,即fattyArray
没有附加值,直到稍后。您应该将调用setChart
的代码移动到findObjectsInBackgroundWithBlock
闭包中。
query.findObjectsInBackgroundWithBlock { percentages, error in
if error == nil {
// build your array like you did in your question
// but when done, call `setChart` here
let months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"]
let unitsSold = fattyArray
setChart(months, values: unitsSold)
} else {
print("\(error?.userInfo)")
}
}
// but not here
// let months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"]
// let unitsSold = fattyArray
//
// setChart(months, values: unitsSold)
您的setChart
例程正在为您提供“索引超出范围”错误,因为您正在遍历dataPoints
,但查找values
数组中的值。我在此处看不到任何内容可以保证months
与fattyArray
中的条目数相同。
显然,如果你修复了第一点,你就更有可能它会起作用(因为在完全检索完数据之前你实际上不会生成图表),但我仍然没有在这里看到任何东西这保证了findObjectsInBackgroundWithBlock
将至少返回六个条目。