Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to create a custom NSNotificationCenter?

Tags:

I've been playing about with the NSNotificationCenter and I've been wondering when you would use your own custom notification center rather than the defaultCenter? And what would the advantages of this be?

Forgive my ignorance, but it seems like I could get along quite happily just using the defaultCenter and nothing else, but I want to make sure I am not missing something vital.

like image 590
Jimmery Avatar asked Jun 11 '13 15:06

Jimmery


People also ask

What is addObserver in Swift?

addObserver(forName:object:queue:using:) Adds an entry to the notification center to receive notifications that passed to the provided block.

What is Nsnotification name?

A structure that defines the name of a notification.

How do I use notification observer in Swift?

First, register an observer for a notification with: addObserver(_:selector:name:object:) Then, post a notification with post(name:object:userInfo:) … … after which your selector is called. And don't forget to remove the observer with removeObserver()


1 Answers

Apple documentation is vague, and it just states that usually a programmer wouldn't need to create a new one:

Each running Cocoa program has a default notification center. You typically don’t create your own. An NSNotificationCenter object can deliver notifications only within a single program.

Full source: NSNotificationCenter documentation.

However every notification center can handle a network of notifications, distinguished by name and object. When you add an observer you typically call the method in some way like this:

[center addObserver: self selector: @selector(observe:) name: @"observe" object: someObject]; 

And when you post a notification you can specify the object:

[center postNotificationName: @"observe" object: someObject]; 

This way say that you use N names and M objects, you can handle N*M distinguished notifications. I think there is no need to use two notification centers. Theoretically if you have finished all names you can create another one using alloc+init, but I hardly see how it can actually turn out handy.

Also consider that notification center is often used when there are two objects that do not own a direct pointer to each other (otherwise why not simply calling a method on it?), due to avoid complicated bindings (specially when you use a lot of xib files), so having an unique notification center object is very handy.

If instead you use a notification center got with allot+init, then you must ensure that all the communicating objects have a pointer to that notification center, and this would add some complexity. All notification center's power would be wasted.

like image 111
Ramy Al Zuhouri Avatar answered Sep 29 '22 12:09

Ramy Al Zuhouri