gpt4 book ai didi

swift - 通知延迟?

转载 作者:可可西里 更新时间:2023-11-01 01:57:06 25 4
gpt4 key购买 nike

今天我遇到了通知延迟的问题。


如果我向 tableView 的数据源数组添加一个新项目,并且我使用通知来更新该 tableView(插入行)(因为它在另一个 ViewController 中),

然后,如果我同时执行 2 次,我的应用程序就会崩溃:因为通知迟到了。


更多详情:

我有一个 TabController:

Chat.shared.receiveMessage { message in

print("1: received msg, added to array")
ChatStore.shared.messages.append(message)

print("2: sending noti")
NotificationCenter.default.post(name: .updateChatMessages, object: nil)

}

还有一个接收 .updateChatMessages 通知的 ChatMessageViewController

@objc func notification_updateChatMessages(){

DispatchQueue.main.async {

print("3: noti arrived")
self.tableView.beginUpdates()
self.tableView.insertRows(at: [IndexPath(row: 0, section: 0)], with: .automatic)
self.tableView.endUpdates()

}
}

问题是,通知以某种方式延迟。

如果同时收到 2 条消息,则会发生以下情况(输出):

1: received msg, added to array

2: sending noti

-

1: received msg, added to array

2: sending noti

-

3: noti arrived

3: noti arrived

应用程序崩溃,因为当第一个通知到达时,两条消息都已添加到数据源中..

相反,输出应该是这样的:

1: received msg, added to array

2: sending noti

3: noti arrived

-

1: received msg, added to array

2: sending noti

3: noti arrived

通知是否延迟?我该如何解决?


UPDATE 1: added receiveMessage() to thread as requested

Chat.swift(接收消息的部分)

func receiveMessage(completion: @escaping (String?)->()){
socket.on("message") {
(data, socketAck) -> Void in
guard let dataArray = data[0] as? [String: Any] else {
return
}
guard let message = dataArray["message"] as? String else {
return
}
return completion(message)
}

}

最佳答案

问题最有可能与使用 DispatchQueue.main.async 有关.这将添加一个要在主运行循环的下一次迭代中运行的闭包。如果在运行循环迭代之间触发了两个通知,那么多个 block 将排队并运行,从而导致您看到的问题。

有几个可行的选项

  • 代码在3: noti arrived之后查看数据存储计算它应该插入多少行。
  • 让聊天商店以线程安全的方式通知观察者,以便通知始终与商店的内容相匹配。
  • 也许使用DispatchQueue.main.sync反而。这在很大程度上取决于您接收套接字消息的队列,并可能导致更严重的问题。

关于swift - 通知延迟?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51541836/

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