不存储值的数组
问题描述:
我从解析后端获取值并使用它们来创建数组,但是没有任何数据存储在其中。有人可以告诉我我做错了什么吗?行:让的DataEntry = ChartDataEntry(值:值[I],xIndex:ⅰ)还给 “索引超出范围”不存储值的数组
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)
}
答
有两个问题这里:
-
的一个问题
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
将返回至少六个条目。
Thanks Rob!那就是诀窍。事情是,虽然我想留下未来几个月没有价值作为激励继续取得进展,并填补他们。有没有办法做到这一点或做ChartDataEntries必须是对? – Nick
我想如果你的图表入口点允许使用可选项(例如'nil'值),那么你可以(a)从你的数据库中检索数据(大概是日期和值对),然后; (b)为这些未来日期手动添加具有日期但没有值的数据点。可能有很多不同的方式来处理这个问题,但从概念上来说,它似乎是可能的。但它似乎超出了这个问题的范围... – Rob
非常感谢您的帮助!所以我找到了另一个我搜索过的问题,发现了一条你曾经评论过的话题,并且想知道你是否不介意看看。我没有50pt的声望,所以我不能评论该线程(http://stackoverflow.com/a/28723081/5109162),但我确实在这里开始另一个http://stackoverflow.com/questions/39137259/UITableView的 - 不使用小区用作为发送器/ 39137309#39137309 – Nick