Possible Duplicate:
What is NSNotification?
what is NSNotification Center ? why is it used ? (iPhone SDK)
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
It is a tool to implement the observer pattern in a generic way. Your objects can say, “I want to be notified if some other object posts a notification so I can do something.” And another object can say, “Something interesting happened, so I’m posting this notification to let others know.”.
In other APIs like Java, you explicitly register as observer to a manager object. The NSNotificationCenter makes this unnecessary (although you still can implement the pattern in exactly this way).
The main idea is decoupling. This means that objects should know as few as possible about each other. NSNotificationCenter is a very valuable tool for that. Before I really knew how to use it, my classes had lots of delegates and sometimes even protocols and register methods so observers could register themselves. Hard to do right. NSNotificationCenter frees you of that burden.
A concrete example: say you got an object that wants to know when the app is terminating. The app delegate has a method that gets called in this case,
applicationWillTerminate:. You can now modify the delegate so that your object can register with the delegate, and implement theapplicationWillTerminate:method so that the registered objects have a method called.Or you do this:
Then you don’t need to even touch your application delegate.
Even cooler is using blocks with
addObserverForName:object:queue:usingBlock:.Just to save you from crashes: if you do register your object as observer, be sure to call the
removeObserver:method of NSNotificationCenter in yourdeallocmethod.I suggest you also read the description in the NSNotificationCenter class reference, it also explains how to use it. Learn to use it, experiment with it, I bet you will find it saves a lot of code sometimes.