what is NSNotification Center ? why is it used ? (

2019-09-24 06:24发布

Possible Duplicate:
What is NSNotification?

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

标签: iphone
1条回答
虎瘦雄心在
2楼-- · 2019-09-24 07:17

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.

查看更多
登录 后发表回答