I used to develop iOS apps using the Objective-C language, and relied on the dealloc
method to perform some cleanup/unregister tasks in my application. Now on the MonoTouch (garbage collected) it is not an option anymore.
Suppose I have a UIViewController
that adds as a subview of it's View
property an instance of MyView
(UIView
subclass). MyView
in turn registers itself to receive some events from another manager/global object so that it knows how to update itself accordingly (e.g.: onlineProfilesManager.Refreshed += () => <update UI with the new state>;
).
As long as MyView
is on screen, everything is fine. However I must know when it's removed from the screen so that I can unregister MyView
from the event handler.
In Obj-C this could be simply done in the dealloc
method because when the screen changes the UIViewController
is deallocated --> MyView
is removed from it's superview and then MyView
dealloc method is called.
In Monotouch I don't have this 'deterministic' flow anymore. I tried to put some print statements in the UIViewController
and MyView
destructors but they are never called (the reason is because the MyView
is still registered for the event handler, since I don't know when/how to unregister it, it will never be deallocated).
Does anyone know what is the 'pattern' to handle such situations in MonoTouch? I think I'm missing a fundamental concept and getting into trouble developing my apps.
Thanks in advance.
EDIT I'm editing my question because looks like the solution for my problem is using the Weak Event Pattern but I didn't find an implementation for the MonoTouch platform.
Does anyone know how can I use the Weak Event Pattern in MonoTouch ?