The principle of KVO and Nsnotificationcenter in Objective-c is a good implementation of the observation pattern, the following code illustrates the usage
The use of KVO
1- (void) Viewdidload {2 [Super Viewdidload];3 //additional setup after loading the view, typically from a nib.4 5Self.model = [modelNew];6 7 //Add Kvo8 [Self.model addobserver:self9Forkeypath:@"name"Ten options:nskeyvalueobservingoptionnew One Context:nil]; A - //send information by modifying the properties -Self.model.name =@"v1.0"; the - } - - #pragmaMark-kvo method +- (void) Observevalueforkeypath: (NSString *) KeyPath Ofobject: (ID)ObjectChange: (Nsdictionary<nskeyvaluechangekey,ID> *) Change context: (void*) Context { -NSLog (@"%@", change); + } A at- (void) Dealloc { - - //Remove Kvo - [Self.model removeobserver:self -Forkeypath:@"name"]; -}
The use of Nsnotificationcenter
1- (void) Viewdidload {2 [Super Viewdidload];3 //additional setup after loading the view, typically from a nib.4 5 //Add6 [[Nsnotificationcenter Defaultcenter] addobserver:self7 selector: @selector (notificationcenterevent:)8Name@" Science"9 Object: nil];Ten One //Send Message A[[Nsnotificationcenter Defaultcenter] Postnotificationname:@" Science" - Object:@"v1.0"]; - the } - - #pragmaMark-Notification Hubs method -- (void) Notificationcenterevent: (ID) Sender { +NSLog (@"%@", sender); - } + A- (void) Dealloc { at //Remove notification hubs - [[Nsnotificationcenter Defaultcenter] removeobserver:self -Forkeypath:@" Science"]; - -}
Use of OBJECTIVE-C observer patterns--KVO and Nsnotificationcenter