Monotouch / iOS:哪个地方是取消订阅代表的最好的地方 [英] Monotouch/iOS: which place is the best one to unsubscribe the delegate

查看:192
本文介绍了Monotouch / iOS:哪个地方是取消订阅代表的最好的地方的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在iOS中订阅事件的最佳方法是ViewDidLoad,但是当关闭视图时,不会调用ViewDidUnload()(仅当内存警告时)。

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?

(在subviewController中,我订阅了一个引用MainViewController的事件,当打开子视图两次时,我收到两个事件触发器因为viewdidunload()中的取消订阅从来没有被调用。)

(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.)

ViewWillAppear / ViewWillDisapper中的订阅/取消订阅如何?

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;          
    }


推荐答案

使用 ViewDidLoad ViewDidUnload ,那些是从UI中订阅/取消订阅活动的适当场所。

Use ViewDidLoad and ViewDidUnload, those are the appropriate places to subscribe/unsubscribe events from the UI.

这是关于iOS内存管理的一般文章,我认为这里适用: http://www.buildingiphoneapps.com/buildingiphoneapps/2010/6/25/memory-management-and-viewdidunload.html

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

现在,如果您不想在View不可见的情况下运行该事件,请在事件处理程序中执行此操作:

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.

这篇关于Monotouch / iOS:哪个地方是取消订阅代表的最好的地方的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆