I am reposting a question I asked on stackoverflow, hopefully someone can help me on this forum.
(I have read http://forums.xamarin.com/discussion/97/correct-way-to-pop-a-dialogviewcontroller-mine-are-staying-in-memory and http://forums.xamarin.com/discussion/4931/summary-of-current-best-practices-for-event-handlers-and-disposing but I am not sure how to implement the suggestions)
I have been using Events instead of delegates in my MonoTouch project, typically using this pattern (iPhone app using Storyboards):
I call PerformSegue to present a new View Controller, and in PrepareForSegue method, I set the View Controller's properties and subscribe to its events using a lambda expression as such:
public override void PrepareForSegue (UIStoryboardSegue segue, NSObject sender)
{
if (segue.Identifier.Equals("NextViewControllerSegue")) {
using (MyNextViewController destinationVC = segue.DestinationViewController as MyNextViewController) {
destinationVC.SomeProperty = "some value";
destinationVC.Cancelled += (s, e) => {
this.DismissViewController(false, null);
};
}
}
}
(as an aside, I chain these Cancelled events where I need to close a hierarchy of View Controllers - whether this is good or bad is a question for another day)
My question is: I recently discovered that if you don't unsubscribe from an object's events, that object is not Garbage Collected. So I have changed the above code to:
public override void PrepareForSegue (UIStoryboardSegue segue, NSObject sender)
{
if (segue.Identifier.Equals("NextViewControllerSegue")) {
using (MyNextViewController destinationVC = segue.DestinationViewController as MyNextViewController) {
destinationVC.SomeProperty = "some value";
destinationVC.Cancelled += Cancel;
}
}
}
protected void Cancel (object sender, EventArgs e)
{
(sender as MyNextViewController).Cancelled -= Cancel;
this.DismissViewController(false, null);
}
My question is this: is this pattern a good way to go about things? And will approach 2 (unsubscribing from the event in the event delegate) work? I am not sure where else to unsubscribe. Or should I move everything to use a notification pattern instead?
Any tips/suggestions greatly appreciated!