【发布时间】:2018-06-01 14:17:06
【问题描述】:
我不确定应该如何使用后台线程中的DispatchQueue.main.async。我应该只将它用于 UI 代码,还是用于所有内容?
哪个更节能?
示例:
仅用于用户界面
worldMessagesFunctions.delete(wmId: cell.worldMessageId) { response in
if let response = response {
if response!.type == 1 {
// Remove value from the source array of the tableView
if let index = WorldMessagesStore.shared.worldMessages.index(where: { $0.id! == cell.worldMessageId }) {
WorldMessagesStore.shared.worldMessages.remove(at: index)
DispatchQueue.main.async {
self.tableView.beginUpdates()
self.tableView.deleteRows(at: [IndexPath(row: index, section: 0)], with: .automatic)
self.tableView.endUpdates()
}
}
print("Okay")
} else {
print("Error")
}
DispatchQueue.main.async {
activityIndicator.stopAnimating()
activityIndicator.removeFromSuperview()
}
}
}
或者从后台线程收到响应后的整体
worldMessagesFunctions.delete(wmId: cell.worldMessageId) { response in
DispatchQueue.main.async {
if let response = response {
if response!.type == 1 {
// Remove value from the source array of the tableView
if let index = WorldMessagesStore.shared.worldMessages.index(where: { $0.id! == cell.worldMessageId }) {
WorldMessagesStore.shared.worldMessages.remove(at: index)
self.tableView.beginUpdates()
self.tableView.deleteRows(at: [IndexPath(row: index, section: 0)], with: .automatic)
self.tableView.endUpdates()
}
print("Okay")
} else {
print("Error")
}
activityIndicator.stopAnimating()
activityIndicator.removeFromSuperview()
}
}
}
【问题讨论】:
-
对我来说,第二个选项更好,只要 api 完成传输主队列中的所有内容并快速执行表操作