Weak event pattern in MonoTouch

I used to develop iOS applications using the Objective-C language and relied on the dealloc method to perform some cleanup / unregister tasks in my application. Now in MonoTouch (garbage collector) this is no longer an option.

Suppose I have a UIViewController that adds a View property of an instance of the MyView subclass ( UIView ) as a subordinate to it. MyView , in turn, registers to receive some events from another manager / global object so that it knows how to update it accordingly (for example: onlineProfilesManager.Refreshed += () => <update UI with the new state>; ).

As long as MyView displayed on the screen, everything is in order. However, I need to know when it is removed from the screen so that I can unregister MyView from the event handler.

In Obj-C, this can simply be done in the dealloc method, because when the screen changes, the UIViewController freed up β†’ MyView is removed from it supervision, and then the MyView dealloc method is MyView .

In Monotouch, I no longer have this deterministic stream. I tried to put some print instructions in the destructors of UIViewController and MyView , but they are never called (the reason is that MyView is still registered for the event handler, since I do not know when / how to unregister it will never be released).

Does anyone know what a β€œpattern” is for handling such situations in MonoTouch? I think that I am missing a fundamental concept and problems with application development.

Thanks in advance.


EDIT I am editing my question because it seems that the solution to my problem is a Weak event pattern , but I did not find an implementation for the MonoTouch platform.

Does anyone know how I can use a weak event pattern in MonoTouch?

+4
source share
2 answers

The best way to handle events is to deregister from ViewWillDisappear and register them with ViewWillAppear. This means that you cannot use anonymous methods, although you do not have a reference to the method to unregister it.

If what you need is not right for you, you can do something similar to this http://sgmunn.com/blog/2012/05/non-gcd-event-handlers/

Greetings.

+6
source

If you are looking for weak events, you can try your implementation of Messenger here .

It is inspired by what is available in TinyIoC , but I reimplemented it to use less reflection, etc.

+1
source

All Articles