问题
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 ?
回答1:
The best way to handle events is to unregister them in ViewWillDisappear and register them in ViewWillAppear. This means that you can't use anonymous methods though as you don't have a reference to the method to unregister it.
If that doesn't suit what you need, you can do something similar to this http://sgmunn.com/blog/2012/05/non-gcd-event-handlers/
Cheers.
回答2:
If you are looking for weak events, you can try my "Messenger" implementation here.
It is inspired by what is available in TinyIoC, but I re-implemented it so it used less reflection, etc.
来源:https://stackoverflow.com/questions/15076905/weak-event-pattern-in-monotouch