什么是更好的方式添加Observer / removeObserver与NSNotificationCenter? [英] What's the better way to addObserver/removeObserver with NSNotificationCenter?

查看:106
本文介绍了什么是更好的方式添加Observer / removeObserver与NSNotificationCenter?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我习惯于 viewDidLoad: removeObserver 中的 addObserver > dealloc:。代码:

I used to addObserver in viewDidLoad: and removeObserver in dealloc:. Code:

- (void)viewDidLoad
{
    [super viewDidLoad];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(refreshData)
                                                 name:AnyNotification
                                               object:nil];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:AnyNotification
                                                  object:nil];
}

但根据一些文章说,在中的 viewDidAppear: removeObserver 视图dDisappear: code>。代码:

But according to some articles said, it's better to addObserver in viewDidAppear: and removeObserver in viewDidDisappear:. Code:

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(refreshData)
                                                 name:AnyNotification
                                               object:nil];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];

    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:AnyNotification
                                                  object:nil];
}

那么,addObserver / removeObserver的更好的方法是什么?

So, what's the better way to addObserver/removeObserver?

推荐答案

这取决于你的场景,通常最好的办法是在 viewDidLoad dealloc viewDidUnload 中,但是有一些情况下,你有相同的方法在不同的类,使用通知只调用当前屏幕的方法,则必须在 viewWillAppear 中添加观察者,并在 viewWillDisappear viewDidAppear / viewDidDisappear

this depends on your scenario, usually the best approach is to add in viewDidLoad and remove in dealloc and in viewDidUnload, but there are some cases when you have same method in different classes like UI effects and want to call only current screen's method using notification, then you will have to add the observer in viewWillAppear and remove it in viewWillDisappear or viewDidAppear/viewDidDisappear

这篇关于什么是更好的方式添加Observer / removeObserver与NSNotificationCenter?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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