增量计数器和 array.count 在使用调度队列时给出不一致的答案

Incremental counter and array.count giving inconsistent answers when using dispatch queue

我有一个简单的应用程序,可以从 CMPedometer 中检索按小时拆分的最近 7 天数据(168 条记录)并将它们存储在数组中。然后,我遍历该数组以找到数组中行进的最高距离,并将其显示在视图的标签中。

    var GlobalMainQueue: dispatch_queue_t {
        return dispatch_get_main_queue()
    }
    var exerciseDataGroup = dispatch_group_create()
    dispatch_group_enter(exerciseDataGroup)
    var modelController = ModelController.init()
    dispatch_group_leave(exerciseDataGroup)


    dispatch_group_notify(exerciseDataGroup, GlobalMainQueue){
        self.BestHourOfTheWeekLabel.text = "Your best distance of the last 7 days was \(modelController.getHighestHourInWeek())"
        }

以上代码在我的viewDidLoad方法中。在 modelController 初始化程序中,我 运行 getDistanceForEachHourInWeek() 检索所有距离记录并填充一个数组来保存它们。

func getDistanceForEachHourInWeek(){
    //****TESTING****
    var count = 0
    var errorCount = 0

    for day in 0...7 {
        //Getting Todays Date
        var today = NSDate()
        let calendar = NSCalendar.currentCalendar()
        //breaking date into components
        var requestedTodaysDateComponents: NSCalendarUnit = .CalendarUnitYear |
            .CalendarUnitMonth |
            .CalendarUnitDay |
            .CalendarUnitHour |
            .CalendarUnitMinute
        var todaysDateComponents = calendar.components(requestedTodaysDateComponents,
            fromDate: today)
        //modifying components to get required date from past 7 days
        todaysDateComponents.day = todaysDateComponents.day - day
        var requestDate = calendar.dateFromComponents(todaysDateComponents)

        for hour in 01...24 {
        //getting start and finish times
        var beginningOfDay = getDateForDaysAgo(day, hour: hour, minutes: 00)
        var endOfDay = getDateForDaysAgo(day, hour: hour, minutes: 59)

        //create a distanceRecord instance for each day
        var recordActivity = distanceRecord.init(startDate: beginningOfDay, endDate: endOfDay)

        //populate the dustanceRecord with data
        self.Pedometer.queryPedometerDataFromDate(beginningOfDay, toDate: endOfDay, withHandler: {activity, error in
            if (error != nil){
                NSLog(" \(error.localizedDescription)")
                ++errorCount
            }
            else{
                //*****TESTING
                ++count
                NSLog("\(count)")
                //add the step counting data
                recordActivity.stepCount = activity.numberOfSteps
                //add the distance data
                recordActivity.distance = activity.distance
                self.hourlyDistanceRecordArray.append(sigActivity)
            }
        })
        }
    }
    NSLog("Finished getting hours, \(count) records & \(errorCount) errors")
}

下面是调用 viewDidLoad 方法更新标签的函数。

func getHighestHourInWeek() -> String {
    var itemsInArray = hourlyDistanceRecordArray.count
    NSLog("\(hourlyDistanceRecordArray.count)")
    var highestValue: Float = 0.0
    var highestDistanceRecord = distanceRecord(startDate: NSDate(), endDate: NSDate())
    for index in 0...itemsInArray {
        if hourlyDistanceRecordArray[index].distance.floatValue > highestValue {
            highestValue = hourlyDistanceRecordArray[index].distance.floatValue
            highestDistanceRecord = hourlyDistanceRecordArray[index]
        }
    }
    return highestDistanceRecord.distance.stringValue
}

我遇到的问题是 getDistanceForEachHourInWeek() NSLog 语句中的增量计数给了我一个数字,getHighestHourInWeek() NSLog 中的 array.count 给了我另一个不同的通常更高的数字,两者都不等于 168 条记录这是我所期待的,而且每次我 运行 它给我的数字也不一致。我尝试使用调度队列解决它,但没有帮助。

我的 NSLog 语句给出了结果(缩短):

1
2
3
...
15
Finished getting hours, 15 records & 0 errors
16
17
18
...
192

谁能帮我指出哪里出错了?为什么代码不等到完成 for 循环后再继续?

我使用 NSNotification 解决了这个问题。

在我的 ModelController 初始化程序中,我添加了

NSNotificationCenter.defaultCenter().addObserver(self, selector: "arrayPopulated", name: arrayPopulated, object: nil)

我修改了 ModelController 中的 getDistanceForEachHourInWeek 函数,以便计步器调用检查我的数组中是否有我预期的记录数 (24 x 7 = 168)

self.Pedometer.queryPedometerDataFromDate(beginningOfDay, toDate: endOfDay, withHandler: {activity, error in
                    if (error != nil){
                        NSLog(" \(error.localizedDescription)")
                        NSLog("ERROR")
                        ++errorCount
                    }
                    else{
                        //XXXXXXXXTESTINGXXXXXXXX
                        ++count
                        tempActivity.stepCount = activity.numberOfSteps
                        //add the distance data
                        tempActivity.distance = activity.distance
                        //Append the tempActivity instance to myActivityArray
                        self.hourlyDistanceRecordArray.append(tempActivity)
                        if count == 168 {
                            NSNotificationCenter.defaultCenter().postNotificationName(self.arrayPopulated, object: self)
                        }
                    }
                })

然后在我的 viewController

的 viewDidLoad 函数中捕获了通知
NSNotificationCenter.defaultCenter().addObserver(self, selector: "actOnArrayPopulated", name: "arrayPopulated", object: nil)

并将我所有的标签更新放入函数中

func actOnArrayPopulated() {
    NSLog("Notification received")
    self.updateScreen()
}

我收到通知和更新屏幕之间似乎仍然有延迟,但它的进度