Swift 调度主队列-正确的方法吗?
我不确定如何从后台线程使用Swift 调度主队列-正确的方法吗?,swift,dispatch,Swift,Dispatch,我不确定如何从后台线程使用DispatchQueue.main.async。我应该只在UI代码中使用它,还是什么都使用它 哪一个更节能 示例: 仅适用于用户界面 worldMessagesFunctions.delete(wmId: cell.worldMessageId) { response in if let response = response { if response!.type == 1 { // Remove value fr
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()
}
}
}
第二个更好。第一种方式是,事情可能以错误的顺序发生,并且您正在跨线程共享WorldMessagesStore 第二个更好。第一种方式是,事情可能以错误的顺序发生,并且您正在跨线程共享WorldMessagesStore 对于我来说,第二个选项更好,只要api完成主队列中的所有传输并快速执行表操作。对于我来说,第二个选项更好,只要api完成主队列中的所有传输并快速执行表操作!!这是我最大的怀疑!!更好的解决方案是在一个单独的串行队列上执行可能长时间运行的解析和更新,并将该单独队列用于与数据存储的所有交互。这样,您就可以避免多线程访问和排序问题。但是,“更好”和“最好”是为什么这是一个“主要观点”的问题:)正是!!这是我最大的怀疑!!更好的解决方案是在一个单独的串行队列上执行可能长时间运行的解析和更新,并将该单独队列用于与数据存储的所有交互。这样,您就可以避免多线程访问和排序问题。但是,“更好”和“最好”是为什么这是一个“主要观点”问题:)