iphone - What is the purpose of NSNotification?

2019-07-18 19:07发布

问题:

  1. Can you please explain what is the purpose of the NSNotification, and what are some situations I could use it?

  2. Does a notification call all classes in the app, or does it call a specific class, by passing a delegate?

  3. Is it possible to create 1 notification, and receive it on multiple classes?

回答1:

  1. Using NSNotification you can notify multiple objects about some event and you can do that not caring about which objects and how many of them are listening for that notification.

  2. NSNotification passes through NSNotificationCenter object that is responsible for getting notifications from objects who create them (using postNotification: functions family) and sending them to the objects who are registered to listen to specific notification (to receive notification object must register in NSNotificationCenter using addObserver: functions)

  3. Notification can be observed by multiple objects - all of them must just register in NSNotificationCenter,



回答2:

NSNotification objects encapsulate information so that it can be broadcast to other objects by an NSNotificationCenter object.

An NSNotification object (referred to as a notification) contains a name, an object, and an optional dictionary. The name is a tag identifying the notification. The object is any object that the poster of the notification wants to send to observers of that notification (typically, it is the object that posted the notification). The dictionary stores other related objects, if any. NSNotification objects are immutable objects.



回答3:

1: Have you read Notification Programming Topics ?

2: Observer should be registred for a notification

3: Yes, several object can observe the same notification