使用 Monotouch 时我应该选择 NSNotificactionCenter 还是 .NET 事件?
在 Monotouch 中开发时,对于我们真正的 .NET event
还是 NSNotificationCenter
来说“更好”?
简单的例子:我有一个 UIViewController。它提供了一个事件“CallbackWhenDisappeared”。该事件在ViewDidDisappear
中触发。有兴趣的可以报名参加活动。
我也可以在 NSNotificationCenter
上发布“MyFancyControllerHasDisappeared”,并让感兴趣的对象在那里订阅。
哪个版本是首选?
我看到的 .NET 事件的缺点是:消失的控制器可能持有对订阅控制器的引用(或者反过来?)并且可能不会被垃圾收集。
与类必须相互了解的事件相比,我还喜欢使用 NSNotificationCenter 时的松散耦合。
有错误或正确的做法吗?
When developing in Monotouch, is it "better" to us real .NET event
s or NSNotificationCenter
?
Simple example: I have a UIViewController
. It offers an event "CallbackWhenDisappeared". This event is triggred in ViewDidDisappear
. Who ever is interested can register to the event.
I could as well post a "MyFancyControllerHasDisappeared" on the NSNotificationCenter
and let interested objects subscribe there.
Which version is to be preferred?
The disadvantage with the .NET events I see: the disappearing controller might hold a reference to the subscribing controller (or the other way round?) and might not be garbage collected.
I also like the loose coupling when using NSNotificationCenter compared to the events where the classes really have to know each other.
Is there a wrong or a right way of doing it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我实际上更喜欢使用 TinyMessenger。与 NSNotifications 不同,它作为框架的一部分为您处理调用的异步性。
托管对象还允许更好的可调试性尤其考虑到这些通常是跨容器调用,我发现这非常有用。
https://github.com/grumpydev/TinyMessenger
I actually prefer to use TinyMessenger. Unlike NSNotifications it handles the asynchronicity of the calls for you as part of the framework.
Managed objects also allow for better debuggability especially considering that these are usually cross container calls I find this to be very very useful.
https://github.com/grumpydev/TinyMessenger
没有真正的正确或错误,但在我看来,它看起来是这样的:
NotificationCenter - 你不知道哪些对象对“事件”感兴趣,你将其发送出去,任何对象都可以接收它
.Net Events - 如果有两个对象之间的直接连接使用此连接,例如 UIViewController 将另一个 UIViewcontroller 显示为 Modal。 ModalUIViewcontroller 会触发一个事件,如果它会隐藏并且 UIViewController 已订阅它
There is no really right or wrong, but in my opinion it looks so:
NotificationCenter - You don't know which Objects are interested on the "Events", you send it out and any object can receive it
.Net Events - If there is a direct connection between two objects use this, for example like an UIViewController shows an other UIViewcontroller as Modal. The ModalUIViewcontroller fires an event, if it will hide and the UIViewController is Suscribed to it