数组不存储值

时间:2016-08-21 04:28:58

标签: arrays parse-platform charts swift2

我从解析后端获取值并使用它们创建数组,但没有任何内容存储在其中。有人可以告诉我我做错了什么吗?行: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)
    }

1 个答案:

答案 0 :(得分:1)

这里有两个问题:

  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)
    
  2. 您的setChart例程正在为您提供“索引超出范围”错误,因为您正在遍历dataPoints,但查找values数组中的值。我在此处看不到任何内容可以保证monthsfattyArray中的条目数相同。

    显然,如果你修复了第一点,你就更有可能它会起作用(因为在完全检索完数据之前你实际上不会生成图表),但我仍然没有在这里看到任何东西这保证了findObjectsInBackgroundWithBlock将至少返回六个条目。