Use of OBJECTIVE-C observer patterns--KVO and Nsnotificationcenter

Source: Internet
Author: User

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

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.