IOS-KVC/KVO

Source: Internet
Author: User

IOS-KVC/KVO

KVC is a tool for setting values. For an object pointing to an id, such as its memory access value. This is a bit like java reflection;

If the next object is known as its property name, the value can be:

id p=[[Person alloc] init];NSString *name=[p valueForKey:@"name"];

Suppose there is an array with a series of objects in it. We want to retrieve a property and put it in a queue, as shown below:

Book *book1=[[Book alloc] init];        book1.name=@"effctive c++";                Book *book2=[[Book alloc] init];        book2.name=@" more effctive c++";                Book *book3=[[Book alloc] init];        book3.name=@" most effctive c++";                NSArray *arr=@[book1,book2,book3];                NSLog(@"%@",[arr valueForKey:@"name"]);

In our daily life, we do have the above requirements;


KVO refers to the process of monitoring a value during the process to verify the business logic.

// Create a Monitored object Book * book1 = [[Book alloc] init]; // set the listening object BookObserve * observe = [[BookObserve alloc] init]; // listen on the stored value-you do not need to remove the listener after this method is used up [observe observeValueForKeyPath: @ "name" ofObject: book1 change: nil context: @ "sadsada"]; // listen on the stored value-02 [book1 addObserver: observe forKeyPath: @ "name" options: NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context: nil]; book1.name = @ "most effctive c ++"; NSLog (@ "% @", book1.name); // cancel listening to its stored value-02 [book1 removeObserver: observe forKeyPath: @ "name"];

No proxy is required for the listener object because it is a derived class of NSObject.

You only need to implement the following method in the. m file to listen:

# Pragma mark keyPath: object property object: object change: dictionary for storing access values-(void) observeValueForKeyPath :( NSString *) keyPath ofObject :( id) object change :( NSDictionary *) change context :( void *) context {}




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.