我不确定如何使用后台线程中的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()
}
}
}
答案 0 :(得分:3)
第二个更好。第一种方式,事情可能以错误的顺序发生,并且您正在跨线程共享WorldMessagesStore。