Do you really know about nsicationicationcenter ?, Nsnotificationcenter

Source: Internet
Author: User
Tags notification center

Do you really know about nsicationicationcenter ?, Nsnotificationcenter

I. First, let's take a look at the definition of nsnotifcenter center.

@ Interface NSNotificationCenter: NSObject {@ package void * _ strong _ impl; void * _ strong _ callback; void * _ pad [11];} // obtain the Message Center Object + (nsicationicationcenter *) defacenter center for a single instance; // Add the first parameter of the message listener to itself, and the second parameter to indicate the method of message callback, the name of the third message notification, and the fourth is nil, which indicates that the message of all senders is accepted-(void) addObserver :( id) observer selector :( SEL) aSelector name :( nullable NSString *) aName object :( nullable id) anObject; // three notification sending methods-(void) postNotification :( NSNotification *) notification;-(void) postNotificationName :( NSString *) aName object :( nullable id) anObject;-(void) postNotificationName :( NSString *) aName object :( nullable id) anObject userInfo :( nullable NSDictionary *) aUserInfo; // remove listener-(void) removeObserver :( id) observer; // remove the listening message-(void) removeObserver :( id) observer name :( nullable NSString *) aName object :( nullable id) anObject; // Add a listener and provide a method to add an observer in block Mode-(id <NSObject>) addObserverForName :( nullable NSString *) name object :( nullable id) obj queue :( nullable NSOperationQueue *) queue usingBlock :( void (^) (NSNotification * note) block NS_AVAILABLE (10_6, 4_0); @ end

Each program has its own notification center, that is, the nsicationicationcenter object. Nsicationicationcenter is also a commonly used message content operation. NSNotificationCenter is a single column. We can use defacenter center to obtain the Single Column of notification center; the notification center is actually a message broadcast mechanism within the iOS program. It is designed to solve the decoupling between different objects in the application. It is designed based on the observer mode and cannot communicate across application processes. After receiving a message, the notification center sends the message to the subscriber based on the internal message forwarding table;

Knowledge Point 1: Steps for using messages

1: Create and send notifications

NSNotification * notification = [NSNotification notifnotifwithname: @ "qjwallet" object: nil userInfo: nil]; // send a notification through the notification center [[nsicationicationcenter defacenter center] postNotification: notification];

2: Register message notifications on the received page

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

3: process and operate the received content

-(Void) qjwalletNotification :( NSNotification *) text {// NSLog (@ "% @", text. userInfo [@ "orderid"]); NSLog (@ "----- received notification ------");}

4: Remove message notifications

-(void)dealloc{    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"qjwallet" object:nil];}

Knowledge Point 2: two other methods for creating a notification and sending it

Method 1: [[nsicationicationcenter defacenter center] postNotificationName: @ "First" object: @ "Center"]; Method 2: NSDictionary * dict = [[NSDictionary alloc] initWithObjects: @ [@ "keso"] forKeys: @ [@ "key"]; [[nsicationicationcenter defacenter center] postNotificationName: @ "Second" object: @ "http://www.cnblogs.com" userInfo: dict];

The above two methods have encapsulated the NSNotification object by one layer, so you only need to pass in the relevant object attributes;

Knowledge Point 3: register the notification NSNotification through nsicationcenter, in viewDidLoad

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationFirst:) name:@"First" object:nil];[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationSecond:) name:@"Second" object:nil];
-(Void) icationicationfirst :( NSNotification *) notification {NSString * name = [notification name]; NSString * object = [notification object]; NSLog (@ "name: % @ ---- object: % @ ", name, object);}-(void) notifseconsecond :( NSNotification *) notification {NSString * name = [notification name]; NSString * object = [notification object]; NSDictionary * dict = [notification userInfo]; NSLog (@ "name: % @ ---- object: % @", name, object); NSLog (@ "value obtained: % @ ", [dict objectForKey: @" key "]);}

Knowledge Point 4: Remove notification messages

-(Void) dealloc {NSLog (@ "The observer has destroyed"); [[nsicationicationcenter defacenter center] removeObserver: self] ;}you can also remove one of them: [[nsicationcenter center defacenter center] removeObserver: self name: @ "First" object: nil];

Knowledge Point 5: If icationicationname is nil, all notifications will be received (if icationicationsender is not empty, all notifications from icationicationsender will be received ). As shown in code list 1. If icationicationsender is nil, all notifications defined by icationicationname will be received; otherwise, notifications sent by icationicationsender will be received. Multiple observers that listen to the same notification are not sure about the order in which the callback is executed when the notification arrives. Therefore, we cannot assume that the operation will be executed in the order of adding the observer.

Knowledge Point 6: differences between addObserverForName and addObserver in Message Processing

In the previous sections, addObserver introduced its four parameters, specifying the notification observer, the callback for processing the notification, the notification name, and the notification sending object. addObserverForName is also used to listen for message processing, but it does not have an observer, but there is an extra queue to process with a block. The addObserverForName parameter description indicates that when name and obj are nil, the situation is the same as that of addObserver in the previous method. If the queue is nil, the message is synchronously processed in the post thread by default, that is, the post and forwarding of the notification are in the same thread; but if we specify the operation queue, the situation becomes a little interesting. Let's talk about it later. The block is copied by the notification center (the copy operation is executed) to maintain a block object in the heap until the observer is removed from the notification center. Therefore, you should pay special attention to using external objects in the block to avoid circular references of objects. If a given notification triggers block operations for multiple observers, these operations will be executed concurrently in their respective Operation Queue. Therefore, we cannot assume that the operation will be executed in the order of adding the observer. This method returns an object that represents the observer. Remember to release this object when not in use.

The instance receives notifications in the specified queue:

@implementation ViewController- (void)viewDidLoad {    [super viewDidLoad];    [[NSNotificationCenter defaultCenter] addObserverForName:TEST_NOTIFICATION object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note) {        NSLog(@"receive thread = %@", [NSThread currentThread]);    }];    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{               NSLog(@"post thread = %@", [NSThread currentThread]);        [[NSNotificationCenter defaultCenter] postNotificationName:TEST_NOTIFICATION object:nil];    });}@end

Here, we add an observer in the main thread and specify to receive and process the notification in the main thread queue. Then we post a notification in a global queue. Let's take a look at the output:

post thread = <NSThread: 0x7ffe0351f5f0>{number = 2, name = (null)}receive thread = <NSThread: 0x7ffe03508b30>{number = 1, name = main}

As you can see, the post and receive processes of messages are not in the same thread. As mentioned above, if the queue is nil, the message is synchronously processed in the post thread by default;

Ii. NSNotification Definition

@ Interface NSNotification: NSObject <NSCopying, NSCoding> // This member variable is the unique identifier of the message object, used to identify the message object @ property (readonly, copy) NSString * name; // This member variable defines an object. It can be understood as a message targeting an object, representing the sender of the notification @ property (nullable, readonly, retain) id object; // This member variable is a dictionary and can be used to pass the value @ property (nullable, readonly, copy) NSDictionary * userInfo; // The initialization method-(instancetype) usage :( NSString *) name object :( nullable id) object userInfo :( nullable NSDictionary *) userInfo NS_AVAILABLE (10_6, 4_0) failed;-(nullable instancetype) failed :( NSCoder *) aDecoder failed; @ end

NSNotification, as its name implies, is the function of a notification. An object notifies another object, which can be used to transmit parameters, communication, and other functions. Unlike one-to-one delegate, a notification is one-to-many. If a notification is registered in an object, any other object can send a notification to this object. Because all attributes are read-only, if you want to create a message, use the following NSNotification (nsnotifcreation) classification method for initialization;

Iii. NSNotification (NSNotificationCreation) Category

@interface NSNotification (NSNotificationCreation)+ (instancetype)notificationWithName:(NSString *)aName object:(nullable id)anObject;+ (instancetype)notificationWithName:(NSString *)aName object:(nullable id)anObject userInfo:(nullable NSDictionary *)aUserInfo;- (instancetype)init /*NS_UNAVAILABLE*/;    /* do not invoke; not a valid initializer for this class */@end

The preceding figure shows the original NSNotification object for sending messages;

Related Article

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.