Explanation of iOS NSNotificationCenter, nsnotificationcenter

Source: Internet
Author: User

Explanation of iOS NSNotificationCenter, nsnotificationcenter

Features of the notification center:

1: Synchronous execution

2: One-to-multiple message sending

3: reducing program Coupling

The notification center is a singleton. It is executed synchronously to send messages to any receiver.

So what is synchronization?

In the classic online saying, I ask a friend to go to dinner. If he doesn't come, I will continue to call. We will not go to dinner until he comes out. This is synchronization; if I ask a friend to go to dinner, whether or not he will come, I will go to dinner first,

This is asynchronous. In the notification center, each message is sent, and the second message is sent only after the message is received and completely executed. This is synchronous, that is, the notification center sends messages one by one, and the next message is executed only after the previous message is executed.

 

Use of NSNotificationCenter:
There are three main steps: registering a notification, sending a broadcast, and destroying a broadcast, and creating a notification.

Defacenter center is used by default, which can be omitted when the notification is not required.

First, we will introduce the declaration method:

 

How to Create a notification:

Method 1 three parameters: name: Notification name object: identifier (nullable id type) userInfo: dictionary type, use

The object parameter should be noted that this parameter is not used to pass the value. If you want to pass the value, userInfo is used, and the object is used to specify the receiving and receiving objects, that is, the receiver filters broadcasts and uses nil when not in use.

NSDictionary *dic = [[NSDictionary alloc]initWithObjectsAndKeys:@"cen",@"ter", nil];[NSNotification notificationWithName:@"center" object:@"center2" userInfo:dic];

The second two parameters are used. The object is not used for passing values.

[NSNotification notificationWithName: @ "center" object: nil]; // not marked // comparison: [NSNotification notificationWithName: @ "center" object: @ "center1"]; // with ID

 

Add observer and register notification

Method 1: Notification object; parameter 2: method; parameter 3: Notification name; parameter 4: Mark (same as before)

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

Method 2 parameter 1: Notification name, parameter 2: identifier, parameter 3: queue, parameter 4: block [the difference with method 1 is that block and queue are used]

[[NSNotificationCenter defaultCenter]addObserverForName:@"ocenter" object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {          }];

 

Send Broadcast

The first parameter type is that notification directly sends the notification object.

[[NSNotificationCenter defaultCenter]postNotification:self.notification];

The second parameter is the same as the previous one.

[[NSNotificationCenter defaultCenter]postNotificationName:@"center" object:nil userInfo:dic];

Third

[[NSNotificationCenter defaultCenter]postNotificationName:@"center" object:nil];

 

Destroy Broadcast

First, destroy the broadcast by the broadcast name.

[[NSNotificationCenter defaultCenter]removeObserver:self name:@"center" object:nil];

Second, destroy broadcast through broadcast object. Note that if detailed objects are not used for destruction, avoid using this method to destroy broadcast. If self is a controller, it may be possible to connect to the system to register

Other notifications are also destroyed. Unless you do not need them together with the system, you can use self.

[[NSNotificationCenter defaultCenter]removeObserver:self.notification];

 

For example:

Step 1: Create a notification

Declaration Method

@ Property (nonatomic, strong) NSNotification * notification;

NSDictionary *dic = [[NSDictionary alloc]initWithObjectsAndKeys:@"cen",@"ter", nil];self.cnotification = [NSNotification notificationWithName:@"center" object:@"user" userInfo:dic];

 

Step 2: Registration notification

The receiver's controller listens to notifications with the name center. You can register notifications in multiple controllers. The notification center can receive notifications without knowing what the receiver is, this can reduce the Coupling Degree of the program.

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

Here, the object filtering effect is used. If the names of multiple notifications created above are all centers, the object filtering function can be used when receiving the notifications.

-(void)tion:(NSNotification *)notification{    if ([notification.object isEqualToString:@"user"]) {        NSLog(@"this's notification is center");    }}

 

Step 3: Send Broadcast

Make a loop Broadcast

Here, notifications are sent with a timer from the place where notifications are created.

[NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(post) userInfo:nil repeats:YES];
-(void)post{       [[NSNotificationCenter defaultCenter]postNotification:self.notification];}

If you create multiple posts to send broadcasts, you can add corresponding methods to verify the synchronization between the one-to-one and the notification center, after each broadcast is sent, the notification center sends a broadcast after the method (such as the tion Method in the example) in the registration notification is executed. No matter how long the method takes, when multithreading is not introduced, it is executed in the order of the sent broadcast. It is executed first, but not in the order in which notifications are registered.

System, of course, the receiving end must have been instantiated before receiving the message. If multithreading is introduced to send the message, it depends on who is first sent in the thread. Of course, it is also the first to send the message first,

 

Step 4: Destroy, for example

[[NSNotificationCenter defaultCenter]removeObserver:self name:@"center" object:nil];

You can use steps 2, 3, and 4 to simplify the process. For example, you need to modify the settings. You can add an object to the registration as needed and add information to the notifications.

 

The issue of observer registration and destruction is also involved.

The creation and destruction of the observer must exist in pairs. One addition corresponds to one destruction.

The created locations include viewWillAppear and viewDidAppear. The destroyed locations include viewWillDisappear, viewDidDisappear, and dealloc.

The notification is registered when the page appears, and removed when the page disappears. Must appear in pairs.AddObserver in viewWillAppearNot inRemoveObserver in viewWillDisappearWhen a message occurs, your method will be called multiple times.

 

Of course, the details are modified as needed. For example, some notifications are used throughout the project and created in appDelegate, if the notification center needs to be used elsewhere and does not need to be destroyed immediately

Destroy, determined from the actual situation.

NSNotificationCenter is here. If something is wrong, you are welcome to point it out.

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.