IOS Nsnotificationcenter Detailed

Source: Internet
Author: User

Features of notification hubs:

1: Synchronous execution

2: One-to-many send message

3: Reduce program coupling degree

The Notification Center is a singleton, which is designed to send a message from any one to any recipient and is executed synchronously.

So what is synchronization?

Using the online classic, that is, I call a friend to eat, if he did not come, I will continue to call, until he came out we eat together, this is the synchronization; If I ask a friend to go to dinner, I will go to dinner, whether he has come or not,

This is asynchronous, in the heart of the notification is every message sent, to wait for the message to be received and complete the inside of the method, and then return to send the second message, which is the synchronization, that is, the notification center sends a message is a single send, and the last message is executed before executing the next.

Use of Nsnotificationcenter:
There are three main steps: Register notification, send broadcast, destroy broadcast, and create a notification.

By default, Defaultcenter is used, and notifications are omitted when they are not required.

Let's introduce the Declaration method:

To create a notification method:

The first method three parameters: Name: Notification Name object: Identity (Nullable ID type) UserInfo: dictionary type, value

Object This parameter to note, in fact, this parameter is not used to pass value, if you want to pass the value, use UserInfo, and the role of object is used to specify the transceiver object, that is, the receiving end of the filter broadcast, do not use nil

Nsdictionary *dic = [[nsdictionary alloc]initwithobjectsandkeys:@ "cen",@ "  ter", nil); [Nsnotification notificationwithname: @" Center " Object:@ "center2" Userinfo:dic];

The second two parameters, object is not a value, ibid.

[Nsnotification notificationwithname:@ "Center"object: nil]; // with no Logo // Comparison: [Nsnotification notificationwithname:@ "Center"object:@ "  Center1"]; // with logo

Adding observers, registering notifications

The first method parameter 1: The object of the notification; parameter 2: method; parameter 3: Name of the notification; parameter 4: Mark (IBID.)

[[Nsnotificationcenter defaultcenter]addobserver:self selector: @selector (otion:) Name:@ "Center " object: nil];

The second method is parameter 1: notification name, Parameter 2: identification, Parameter 3: queue, Parameter 4:block[with Method 1 is used block and queue]

[[Nsnotificationcenter Defaultcenter]addobserverforname:@ "ocenter"object: Nil Queue:[nsoperationqueue Mainqueue] usingblock:^ (nsnotification * _nonnull Note) {          }];

Send broadcast

The first parameter type is notification send the notification object directly out of the

[[Nsnotificationcenter defaultcenter]postnotification:self.notification];

The second parameter is the same as the previous one.

[[Nsnotificationcenter Defaultcenter]postnotificationname:@ 'center'object: Nil Userinfo:dic];

Third Kind

[[Nsnotificationcenter Defaultcenter]postnotificationname:@ 'center'object: NIL];

Destroying broadcasts

The first to destroy the broadcast by means of a broadcast name

[[Nsnotificationcenter defaultcenter]removeobserver:self Name:@ 'center'object : nil];

The second is to destroy the broadcast through a broadcast object. Note that if you do not use the detailed object to destroy, then try to avoid using this method to destroy the broadcast, if Self is the controller, it may even register the system itself

Other notices are also destroyed together, unless the part of the system is also not available, self

[[Nsnotificationcenter defaultcenter]removeobserver:self.notification];

As an example:

First step: Create a notification

How to declare

@property (Nonatomic,strong) nsnotification *notification;

Nsdictionary *dic = [[nsdictionary alloc]initwithobjectsandkeys:@ "cen",@ "  ter"= [nsnotification notificationwithname:@"Center"  Object:@ "user" Userinfo:dic];

Step Two: Registration notice

Receiver's controller to listen to the name of the center of the notification, can be registered in multiple controllers notification, and Notification Center does not know what the receiver is, the receiver can also receive, which can reduce the coupling degree of the program

[[Nsnotificationcenter defaultcenter]addobserver:self selector: @selector (tion:) Name:@ "Center " object: nil];

This uses the filter effect of the object, if the above create more than one notification name is center, then you can use object filter when receiving

-(void) tion: (nsnotification *) notification{    if ([Notification.  Object isequaltostring:@ "user"]) {        NSLog (@ "  This ' s notification is center");}    }

Step three: Send a broadcast

Make a loop-sent broadcast

Here, use the timer to send notifications from the place where you created the notification.

[Nstimer scheduledtimerwithtimeinterval:2 target:self selector: @selector (POST) Userinfo:nil Repeats:yes];
-(void) post{       [[Nsnotificationcenter defaultcenter]postnotification:self.notification];}

If you create multiple post-send broadcasts, you can add a corresponding method to verify the synchronization of a one-to-many and notification hubs in the notification hub, and the notification hub waits for the method in the registration notification (such as the Tion method in the example) to be sent after each broadcast, regardless of how long it takes to execute the method. In the absence of multi-threaded, in order to send the broadcast sequence execution, first sent first execution, with the creation of the registration notification sequence is not relevant

, of course, the receiver must have been instantiated to receive, if the introduction of multi-threaded send messages, it depends on the thread who was sent first, of course, the first to send the first execution,

The fourth step: Finally, the destruction, for example

[[Nsnotificationcenter defaultcenter]removeobserver:self Name:@ 'center'object : nil];

Simplified use, 2, 3, 4 steps can be used, the example needs to be modified, you can add an object from the registration as needed, and send the notification to take information

It also involves the registration and destruction of observers.

Observer creation and destruction to be in a pair of existence, one time to add the corresponding destruction

Locations such as Viewwillappear and Viewdidappear, where they are destroyed such as Viewwilldisappear, Viewdiddisappear, and Dealloc

is to register the notification when the page appears, and remove the notification when the page disappears. Be sure to show up in pairs, and if you're only in the viewWillAppear 中 addObserver absence viewWillDisappear 中 removeObserver of a message, your method will be called multiple times.

Of course, in detail or as needed to modify, such as some notice is used throughout the project, created in the appdelegate, if the notification center in other places need to be used without immediate destruction, the use of the completion of the

Destroyed, determined from the actual situation.

Nsnotificationcenter is here, and if there's something wrong, you're welcome to point out

IOS Nsnotificationcenter Detailed

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.