看了那么多并行和并发的帖子,我还是很迷惑什么才是正确的取数据方式。例如,在我的项目中,我有一个供用户获取数据的按钮。我的代码如下所示。
var array = [Int]()
func fetchData() {
....
....
response(objects: [object], error: NSError?) {
for object in objects {
array.append(object.number) // assume object.number return an Int
}
// confuse here. Should I use async here because I am worry if the user
// click the fetchData button more than one time, the append and make
// function will be happened at the same time. Or, is there anything I
// made a wrong assumption? I guess I need a serial operation. Correct?
dispatch_async(dispatch_get_main_queue()) {
makeCollectionView() // using the data in array
}
}
}
更新
尝试运行此代码。 10000-19999 在 0-9999 之后运行。似乎第二个异步不会停止第一个异步来处理它的操作。
dispatch_async(dispatch_get_main_queue(), { () -> Void in
for i in 0 ..< 10000 {
print(i)
}
})
dispatch_async(dispatch_get_main_queue(), { () -> Void in
for i in 10000 ..< 20000 {
print(i)
}
})
最佳答案
为了提高性能,任何涉及 UI 的东西都应该在主线程上运行。所以基本上:
dispatch_async(dispatch_get_main_queue()) {
//anything that involves UI
}
关于swift - dispatch_async 与 dispatch_sync 在获取数据中的对比。 swift ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39011078/