Nsnotification is notification, you can implement an object to send notifications, multiple objects receive notifications.
Work Flow:
Add a notification hub (singleton) to the class that needs to send notifications.
Send a notification in the class that needs to send the notification, the object that sent the notification is self, you can define the appropriate user information, the notification name can be any defined string, and the listener notification needs to match this notification name.
In the class that needs to receive the notification, the receiving object is added to listen for the notification, and the corresponding method of the recipient is defined below, and the method name is encapsulated to the receiving object above.
Finally, the notification of the listener of the current object is removed.
Example: send a notification in your child's class, tell your child to be dirty, receive a notification in the Nanny class, and implement a bath for your child.
#import "Child.h" @implementation child-(instancetype) init {if (self = [super init]) {_cleanvalue = 100; _happyvalue = 100; } [Nstimer scheduledtimerwithtimeinterval:1 target:self selector: @selector (timeraction:) Userinfo:nil Repeats:yes]; return self;} -(void) Timeraction: (Nstimer *) timer {_cleanvalue--; _happyvalue--; NSLog (@ "Cleanvalue:%li, Happyvalue:%li", _cleanvalue, _happyvalue); if (_cleanvalue = = 95) {//Get to notification hubs object--Singleton, there is only one notification hub object in memory nsnotificationcenter *center = [Nsnotifica Tioncenter Defaultcenter]; Send notification, with user information//user information can be no, the latter is printed out nsdictionary *userinfo = @{@ "name": @ "Tengteng" @ "Age": @ "22"}; [Center postnotificationname:@ "Bathnotification" object:self Userinfo:userinfo]; }} @end
#import "Nanny.h" #import "Child.h" @implementation nanny//to respond to this event after receiving notification-(Instancetype) init { if (self = [super Init]) { //Listener notification nsnotificationcenter *center = [Nsnotificationcenter defaultcenter]; [Center addobserver:self selector: @selector (cleanvalueaction:) name:@ "Bathnotification" Object:nil]; } return self;} -(void) Cleanvalueaction: (nsnotification *) Notification { //nanny responds to the child's dirty response NSLog (@ "The babysitter washes the child"); Get to the sender of the notification, the child, so that you can change the child's cleanliness of the property *child = (children *) Notification.object; The Information NSLog (@ "userinfo:%@", notification.userinfo) can be obtained by notification to the sender of the notification; Child.cleanvalue = 100;} -(void) Dealloc { //Remove the current object from listening to all notifications [[Nsnotificationcenter Defaultcenter] removeobserver:self];} @end
Nsnotification of iOS development ———— communication methods