开发者

what is NSNotification Center ? why is it used ? (iPhone SDK) [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

What is NSNotification?

what is NSNotification Center ? why is开发者_运维知识库 it used ? (iPhone SDK)


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 the applicationWillTerminate: method so that the registered objects have a method called.

Or you do this:

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(aMethodOnMyObject)
                                             name:NSApplicationWillTerminateNotification
                                           object:nil];

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 your dealloc method.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜