Suppose you have an iOS app with a UINavigationController with three UIViewControllers pushed onto it: vc1, vc2 and vc3.
vc1 wants to get notified of when something happens on vc2 and/or vc3. For example, when something gets saved on vc2 or vc3, update vc1 and automatically pop back to vc1. Easy. Just have vc2 or vc3 fire an event and have it be caught by vc1. Well, when the time comes to pop back to vc1 the other two vc’s won’t get garbage collected because they hold a reference via the event subscription.
What’s the best way to resolve this and get everything cleaned up when vc1 subscribes to an event on vc2, similarly vc2 to vc3?
Only thing I can think of is to define a public CleanUp() method so that when the nav controller pops back to vc1 (and vc1 will have to detect this scenario somehow) it will call vc2.CleanUp(). If you had X number of vc’s that would be a lot of cleanup that you’d have to write ’cause you’d have to, in a sense, bubble up the call through the line of popped vc’s. Yuck.
How would you do this traditionally in obj-c and also, how would you do this in MonoTouch?
I am using the scenario you are describing above quite frequently. This is how I handle it:
Controller vc1 pushes vc2 onto the navigation stack, after it has subscribed to vc2’s SaveClicked event. So I want to pop vc2 when this event occurs. Now, since vc2 will be popped when the SaveClicked event will be triggered, it suits us because we know that the event will only be used once. I also use anonymous methods for these situations when not much logic is needed, to keep things compact.
Inside vc1:
So you can do the same for vc2 and vc3 and so on…