Swift-使用NotificationCenter观察价值变化真的不好吗?

发布于 2025-02-10 19:34:46 字数 275 浏览 1 评论 0原文

只是一个初学者的问题。我希望有人可以帮助我。我正在搜索在Swift中在全球观察变化变化的最佳方法。我遇到了一些文章,说使用NotificationCenter是一个不好的选择,我们应该尽可能避免它。他们建议使用代表和依赖注入。我正在为可重复使用的UI组件使用Delagates。

但是我有一个Websocket连接。我每秒收到此套接字的数据,此数据用于不同的和多个视图控制器(4-6 VC)。现在,我正在使用通知中心,该通知中心收到新数据时通知所有这些VC。

这是正确的方法还是您可以推荐我正确的方法?谢谢。

Just a beginner question. I hope someone can help me. I am searching the best way to observe variable change globally in swift. And I encountered some article that says using NotificationCenter is a bad choice and we should avoid it as much as possible. They are suggesting using delegates and dependency injection. I am using delagates for my reusable UI components.

But I have a websocket connection. I received data from this socket every second, this data are being used in different and multiple view controllers (4-6 VCs). Right now, I am using NotificationCenter that notifies all these VCs when I received new data.

Is this the right approach or can you recommend me the correct way to do this? Thank you.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

行雁书 2025-02-17 19:34:46

根据应用程序的部署目标,您可以考虑使用组合传播Websocket事件:

联合收割机框架为随着时间的推移处理值提供了声明的Swift API。这些值可以代表多种异步事件。将声明的发布者结合在一起,以揭示可以随时间变化的值,并从发布者那里接收这些值。

https://develoveling.apple.apple.apple.com/documentation/combine

Depending on the deployment target of your app, you could consider using Combine to propagate websocket events:

The Combine framework provides a declarative Swift API for processing values over time. These values can represent many kinds of asynchronous events. Combine declares publishers to expose values that can change over time, and subscribers to receive those values from the publishers.

https://developer.apple.com/documentation/combine

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文