IOS Study Notes 8-KVO and KVC

Source: Internet
Author: User

KVO and KVC are short for Key-Value Observing and Key-Value Coding respectively. I think of this topic because the update of the tableView I wrote is polling every few seconds. I was wondering if I needed a mechanism similar to triggering the update. This naturally comes to mind the observer mode.

Search for the Observer Pattern of Objective-c and find that there are two ways to achieve it in the http://stackoverflow.com/questions/165790/whats-the-nicest-way-to-do-observer-observable-in-objective-c-iphone-version: nsicationicationcenter and KVO. In the answer, it is described that Notification is old and heavy... Although I have studied it a little, I 'd like to discuss it next time.

 

1. KVC

Isn't it KVO? Why do we need to talk about KVC first? The Mac Developer Library says that KVC is the preparation knowledge of KVO. Okay. Let's take a look at KVC.

KVC is a non-direct access to object attributes. What is direct access? Get and set.

If we omit the overhead, KVC obtains the value through the key.

Something like Dictionary? Well, in a sense, it is far more.

In Objective-C, there is also a dictionary class NSDictionary. You can use the objectForKey method to obtain the value corresponding to a key. However, KVC canAllClass to obtain the value of a property (key ).

Let's take a look at the sample code. For example, there is a class:

@interface TestClass : NSObject@property NSInteger integerProperty;@property TestClass *linkedInstance;@end

You can use a traditional set to assign values. For example:

    TestClass *anotherInstance = [[TestClassalloc] init];    myInstance.linkedInstance = anotherInstance;    myInstance.integerProperty = 2;

However, you can also assign values using kvc:

    TestClass *anotherInstance = [[TestClass alloc] init];    myInstance.linkedInstance = anotherInstance;    [myInstance setValue:@2forKeyPath:@"linkedInstance.integerProperty"];

From this perspective, KVC is similar to some reflection functions in. NET.

As described above, to use the KVC value, you can use valueForKey.

Because it is a language-level function, KVC can implement powerful functions. For example:

Obtain one or more: objectAtIndex, objectsAtIndexes, count,-get <Key>: range:

Add, delete, modify, and delete: insertObject, insertObjects, removeObjectAtIndex, replaceObjectAtIndex,

 

2. KVO

KVO allows an object to know that a property of another object has been modified. It is widely used in the interaction between MVC model and controller layer.

Three steps are required to implement KVO:

1) Specify the notification object and notification object

For example, if the deposit is changed, for example, 5000 Yuan is withdrawn, the account owner needs to be notified. In this scenario, the notification object is the bank account, and the notification object is the account owner.

 

2) The notified object registers the observer for a certain attribute in the notification object.

Syntax: addObserver: forKeyPath: options: context:

For the example above, the owner needs to register an observer in the account instance.

Sample Code:

[Account addObserver: inspector

ForKeyPath: @ "openingBalance"

Options :( NSKeyValueObservingOptionNew |

NSKeyValueObservingOptionOld)

Context: NULL];

The option parameter indicates the value before and after the property is changed.

In addition, it can be added or removed with removeObserver.

 

3) implemented observeValueForKeyPath by the notification object (observer)

This method is used to implement what the observer will do after being notified

For the above example, if the observer determines whether he has made a withdrawal or a shopping operation, and then decides whether to trigger an alarm?

Sample Code:

- (void)observeValueForKeyPath:(NSString *)keyPath                      ofObject:(id)object                        change:(NSDictionary *)change                       context:(void *)context {    if ([keyPath isEqual:@"openingBalance"]) {        [openingBalanceInspectorField setObjectValue:         [change objectForKey:NSKeyValueChangeNewKey]];    }    /*     Be sure to call the superclass's implementation *if it implements it*.     NSObject does not implement the method.     */    [superobserveValueForKeyPath:keyPath                         ofObject:object                           change:change                          context:context];}

 

 

References:

Key-Value Coding Programming Guide

Https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/KeyValueCoding/Articles/KeyValueCoding.html%23//apple_ref/doc/uid/10000107-SW1

 

Key-Value Observing Programming Guide

Http://developer.apple.com/library/mac/#documentation/cocoa/conceptual/KeyValueObserving/KeyValueObserving.html%23//apple_ref/doc/uid/10000177-BCICJDHA

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.