Should I prefer NSNotificactionCenter or .NET events when using Monotouch?

老子叫甜甜 提交于 2020-01-05 12:34:24

问题


When developing in Monotouch, is it "better" to us real .NET events 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?


回答1:


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




回答2:


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.

var messageHub = new TinyMessengerHub();
// Publishing a message is as simple as calling the "Publish" method.
messageHub.Publish(new MyMessage());

// We can also publish asyncronously if necessary
messageHub.PublishAsync(new MyMessage());

// And we can get a callback when publishing is completed
messageHub.PublishAsync(new MyMessage(), MyCallback); 
// MyCallback is executed on completion

https://github.com/grumpydev/TinyMessenger



来源:https://stackoverflow.com/questions/7612448/should-i-prefer-nsnotificactioncenter-or-net-events-when-using-monotouch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!