How NSNotification Works

I understand that in the notice, the poster and the observer.

But I absolutely do not understand how our application or OS understands and sends a flag / notification to the observer class?

What is the mechanism of this?

Your response and help will be appreciated very often.

thanks

ID

+4
source share
4 answers

Imagine the Notification Center as a dictionary that has keys for notification names and values ​​for the observer list (and their specific action methods). When a notification is sent, the observer list for this notification name is received and repeated. Each observer has an action method called with notification information.

In addition, during the iteration, there is a check to determine if the notification object is of interest to the observer (based on the parameters provided when adding the observer).

The notification process runs in the thread from which the notification was sent.

Do not think about trying to rely on any implied order related to how and when observers were added.

+5
source

Basically, NotificationCenter maintains a link to any object that is registered as an observer. With this link, it also keeps track of which notifications the objects want. When an object sends a notification, the center passes it to each registered observer, sending a message to the observer with this selector.

The default center is usually a global single. But you can create your own, perhaps if you want your notifications to be private to your application.

+4
source

To send a notification, the object sends:

[[NSNotificationCenter defaultCenter] postNotificationName:@"notif_key" object:nil userInfo:userDict]; 

Now every living object that listens for a notification with the name @ "notif_key" can perform some action.

How do you create an object to listen to?

It should run:

 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(doSomething:) name:@"notif_key" object:nil]; 

. When the first object sends a notification, the watcher will invoke the doSomething: method.

Notes:

  • userDict is a dictionary where you can send some information to these observers.
  • Remember to cancel the observer in the dealloc method.
+1
source

Add this to your understanding, and it took me a while to digest my head. Although he does not show how it works inside, it tells how it is implemented to work

In a multi-threaded application, notifications are always sent to the stream in which the notification was sent , which cannot be the same stream in which the observer registered himself.

Source: Apple Documentation

Thus, a notification can be registered in any stream, but the method associated with the notification starts in the stream on which the notification was sent, therefore, if we want to make any changes to the user interface, we send it to the main stream.

0
source

Source: https://habr.com/ru/post/1488928/


All Articles