BlueSky BlueSky - 2 years ago 78
iOS Question

Monotouch/iOS: which place is the best one to unsubscribe the delegate

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;

Answer Source

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:

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download