The notification is actually similar to KVO. It is to set a notification in Class A first, and then set a method to listen to the notification in Class B. Of course, some parameters can be passed through this notification method, after this parameter is obtained, an action is generally triggered. The example here is to trigger the output of some content.
(1) Initialize an instance variable of 100 in the Child class, and decrease by 2 each time. A notification is triggered when the value is less than 90.
//Child.h#import <Foundation/Foundation.h>@interface Child : NSObject@property(nonatomic,assign)NSInteger sleep;@end
// Child. M # import "child. H" @ implementation child-(ID) Init {self = [Super init]; If (self! = Nil) {_ sleep = 100; // The Initialization is 100 [nst1_timerwithtimeinterval: 1 target: Self selector: @ selector (Action :) userinfo: Nil repeats: Yes]; // set a timer and return the sleep to return self;} // The following is the descending function-(void) Action :( nstimer *) timer {_ sleep-= 2; // when conditions are met, the notification if (_ sleep <90) {// set is triggered. The name is helloname and the object is a number of parameters, sometimes the parameter [[nsnotificationcenter defaultcenter] postnotificationname: @ "helloname" Object: [nsnumber numberwithinteger: _ sleep]; [Timer invalidate] may be included in the notification; // when the value is less than, stop the timer after the timer is sent} @ end
(2) set the listener notification in the parent class. If the notification is detected, the output of the Action method definition is triggered.
// Parent. M # import "parent. H" # import "child. H" @ implementation parent-(ID) Init {self = [Super init]; If (self! = Nil) {// Add a notification listener [[nsnotifcenter center defaultcenter] addobserver: Self selector: @ selector (wakemove :) name: @ "helloname" Object: Nil];} return self;}-(void) wakemove :( nsnotification *) Notice {// You can also add a parameter userinfo to the notification with the child settings: What is a dictionary or something after DIC, then use notice. the userinfo output can be nsnumber * num1 = notice. object; // pass the object defined in the Child notification to nslog (@ "hold on the baby, % @", num1);} @ end
(3) Main. m
#import <Foundation/Foundation.h>#import "Child.h"#import "Parent.h"int main(int argc, const char * argv[]){ @autoreleasepool { Child *child1=[[Child alloc]init]; Parent *parent1=[[Parent alloc]init]; [[NSRunLoop currentRunLoop]run]; } return 0;}
Well, there is a problem with the output results, but the reason is still unclear.
The concept and usage of notifications are similar to those of KVO.
This is used in project development.
[OC learning-34] Notification nsnotification, similar to KVO, used for listening between objects and sending notification notifications