KVC and KVO in IOS development, ioskvckvo

Source: Internet
Author: User

KVC and KVO in IOS development, ioskvckvo

KVC: Key-Value Coding

KVO: Key-Value Observing

 

Person. m

@ Interface Person: NSObject {// This access modifier is used to indicate that even private member variables can be accessed and assigned @ private NSString * _ name through kvc ;} @ end @ implementation Person @ end

PersonObserve. m

@ Interface PersonObserve: NSObject @ end @ implementation PersonObserve-(void) observeValueForKeyPath :( NSString *) keyPath ofObject :( id) object change :( NSDictionary *) change context :( void *) context {Person * p = (Person *) object; // obtain the NSLog (@ "% @", [p valueForKey: keypath]) of the keyPath of the member variable using kvc;} @ end

Main. m

Int main (int argc, const char * argv []) {// observer class PersonObserve * po = [[PersonObserve alloc] init]; person * p = [[Person alloc] init]; // use kvo to increase the value of the member variable "name". The observer po // po will be executed when the value changes-(void) observeValueForKeyPath :( NSString *) keyPath ofObject :( id) object change :( NSDictionary *) change context :( void *) context method [p addObserver: po forKeyPath: @ "name" options: NSKeyValueObservingOptionNew context: nil]; // set the attribute value of the member variable "name" in kvc mode. // The starting observer executes the corresponding method [p setValue: @ "yangys" forKey: @ "name"]; // remove the observation of the Private member variable "name" [p removeObserver: po forKeyPath: @ "name"]; return 0 ;}

Result:

2015-03-02 20:57:52.487 KVC&KOC[843:24874] yangysProgram ended with exit code: 0

 

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.