问题
The best method in iOS to subscribe a event is ViewDidLoad, but when dismiss the view , the ViewDidUnload() is not called(only when the memory warning.)
Which place is the best to unsubscribe the event?
(In the subviewController I subscribe a event that reference the MainViewController, When open the subview twice, I receive two event trigger because the unsubscribe in viewdidunload() is never called.)
How about with subscribe/unsubscribe in ViewWillAppear/ViewWillDisapper?
public override void ViewWillAppear (bool animated)
{
base.ViewWillAppear (animated);
this.mBL.OrderChanged += HandleOrderChanged;
}
public override void ViewWillDisappear (bool animated)
{
base.VieWillDisappear (animated);
if (this.mBL!=null)
this.mBL.OrderChanged -= HandleOrderChanged;
}
回答1:
Use ViewDidLoad
and ViewDidUnload
, those are the appropriate places to subscribe/unsubscribe events from the UI.
Here is a general article on memory management in iOS that I think applies here: http://www.buildingiphoneapps.com/buildingiphoneapps/2010/6/25/memory-management-and-viewdidunload.html
Now, if you're not wanting to have the event run when your View is not visible, do something like this in the event handler:
if (IsViewLoaded && View.Window != null) {
//code here
}
I've found this is the easiest way to tell if the view is on screen.
回答2:
I agree, the best time is in ViewWillAppear/ViewWillDisappear, not ViewDidUnload.
ViewDidUnload is called called post iOS 6: https://developer.xamarin.com/api/member/UIKit.UIViewController.ViewDidUnload()/
来源:https://stackoverflow.com/questions/10155281/monotouch-ios-which-place-is-the-best-one-to-unsubscribe-the-delegate