Where is the best place to put "[NSNotificationCenter defaultCenter] addObserver"

I'm used to putting "[NSNotificationCenter defaultCenter] addObserver" in the init method. And I've seen many others add to viewDidLoad. Is there any guidance or best practice?

Liang

+3


source to share


2 answers


I would say it is fair, it doesn't really matter. My opinion is that this is best in viewDidLoad, but like @EricS, if you want to be notified when the view is not displayed, this won't work for sure. So it really depends on how you prefer to use it and when you want to be notified of these events.



0


source


Two questions to ask yourself:

  • Can this notification be triggered between the launch of the UIViewController and the loading of its view?

  • If a notification can be triggered between these events, does your UIViewController state matter?



These questions will help you in which method to call addObserver internally. There is no particular "best practice" other than this:

Only listen when you need to.

0


source







All Articles