fannheyward fannheyward - 6 months ago 36
Objective-C Question

What's the better way to addObserver/removeObserver with NSNotificationCenter?

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


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


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

Answer

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

Comments