什么是更好的方式添加Observer / removeObserver与NSNotificationCenter? [英] What's the better way to addObserver/removeObserver with 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屋!