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

cocoa-touch, iphone, objective-c

Solution

this depends on your scenario, usually the best approach is to add in `viewDidLoad` and remove in `dealloc` and in `viewDidUnload` (deprecated in iOS 9.0, use `dealloc` only), 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`

Edit: A note from comments, thanks @honey.

Though now since iOS 9, you no longer need to care about removing the observer. See Apple release notes: "In OS X 10.11 and iOS 9.0 NSNotificationCenter and NSDistributedNotificationCenter will no longer send notifications to registered observers that may be deallocated..

Problem

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?

Original source