gpt4 book ai didi

ios - Swift 中的 Grand Central Dispatch 仅在第一次运行时有效

转载 作者:行者123 更新时间:2023-11-29 01:22:45 24 4
gpt4 key购买 nike

我得到了一个类似于复习的方法,它使用 GCD 模式,如下所示:

    func getStepsForTheWeek() {
let concurrentQueue : dispatch_queue_t = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)

dispatch_async(concurrentQueue, {

// Create an array of Days.
var days = [Day]()

dispatch_sync(concurrentQueue, {
print("first")

for day in 0...7 {

let date = self.getDate(day)

// Get the date the day after that day.
let endDate = self.getDateDayAfter(date)

// Create a Day.
var day = Day(date: date)

self.pedometer.queryPedometerDataFromDate(date, toDate: endDate, withHandler: {numberOfSteps, error in
print("fetching")

if error != nil {
print("There was an error requesting data from the pedometer: \(error)")
} else {
day.steps = numberOfSteps!.numberOfSteps as Int
days.append(day)
}
})
}
})

dispatch_sync(dispatch_get_main_queue(), {
print("second")

self.historyViewController.days = days
self.historyViewController.reloadHistory()
})
})
}

当应用程序启动时,该方法将按预期工作。但是当应用程序处于后台并且当我返回应用程序时,我得到了这个 Observer,它再次调用该方法来刷新其内容。

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

但是每次我这样做时,第二个代码块都会在第一个代码块之前运行。有帮助吗?

最佳答案

我认为您应该在计步器查询的完成处理程序中进行 UI 更新

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), {

self.pedometer.queryPedometerDataFromDate(date, toDate: endDate, withHandler: { numberOfSteps, error in
if error != nil {
print("There was an error requesting data from the pedometer: \(error)")
} else {
let numberOfStepsThisDay = numberOfSteps?.numberOfSteps as! Int

day.steps = numberOfStepsThisDay
days.append(day)
}

dispatch_async(dispatch_get_main_queue(), {
self.historyViewController.days = self.days
self.historyViewController.reloadHistory()
})
})
})

你应该总是在方法的完成处理程序中更新 UI,如果它有一个,因为你不知道它是否可以是异步的(如果使用完成处理程序通常是异步的),你可能会删除外部dispatch_async 如果除了计步器查询之外没有其他代码

关于ios - Swift 中的 Grand Central Dispatch 仅在第一次运行时有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34407753/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com