IOS KVC & KVO

Source: Internet
Author: User

Key Value Coding

Key Value Coding is a standard component of cocoa, which allows us to access the property by name (key) without having to invoke the explicit property accssor, as we have a property called Foo, We can get Foo to access it directly, we can also use KVC to complete the [Object valueforkey:@ "foo"], some students will ask, what is the benefit of doing this? The main benefit is to reduce the amount of code we have.

Let's take a look at a few examples and understand the usage and benefits of KVO, assuming such a class is called people,

123456 @interface People: NSObject@property (nonatomic, strong) NSString *name;@property (nonatomic, strong) NSNumber *age;@end

Scene 1,apple An example of the official website, when we need to count a lot of people, each row is an instance of a person, and there are 2 columns of properties, name, age, which we can do,

123456789101112 - (id)tableView:(NSTableView *)tableview      objectValueForTableColumn:(id)column row:(NSInteger)row {    People *people = [peoleArray objectAtIndex:row];    if ([[column identifier] isEqualToString:@"name"]) {        return [people name];    }    if ([[column identifier] isEqualToString:@"age"]) {        return [people age];    }    // And so on.}

We can also use KVC to help us simplify these if, because name, age is actually the property, we can directly through the key to access, so after finishing is

12 People *people = [peopleArray objectAtIndex:row];return [people valueForKey:[column identifier]];

Scenario 2, we have a server, a server API (Listpeople??), will return our JSON format an array containing such dict{name:xx, age:xx} such data, We want to use these dict data to construct our people, and it is usually our practice to write a static factory method for our people class to handle dict, remove the data from the Dict, and then create an empty people object. Then set the property in turn. However, when such a similar people with the server to interact with the class, we will have to add such a wrapper for each class, whether there is a simple way to set such a property, of course, our KVC.

123456789 -(ID) initwithdictionary: (nsmutabledictionary*) Jsonobject {      if (self = [super init])      {          [self init];          [self Setvaluesforkeyswithdictionary:jsonobject];      }      return self; }

Setvaluesforkeyswithdictionary, will be for us and dictionary key name of the same class Proerty set on the Dict key corresponding value, is not very convenient ah, but some students have to ask If some key in JSON is not the same as the property name of object, or some of the fields returned by the server are OBJC reserved words such as "id", "description", etc., we also want to also map dict to object, At this point we need to use the Setvalue:forundefinedkey, because if we do not deal with these undefined Key, or setvaluesforkeyswithdictionary will throw an exception.

123456789 -(void) SetValue: (ID) Value Forundefinedkey: (NSString *) key {       if ([Key isequaltostring:@ "Namexxx"])          self.name = value;      if ([Key isequaltostring:@ "Agexxx"])          self.age = value;      else          [super Setvalue:value Forkey:key]; }

So as long as this method is overloaded, you can deal with the key that cannot match the property, the default implementation is to throw a nsundefinedkeyexception, and the classmate asked if the server returned people with embedded JSON ( such as Products{product1{count:xx, Sumprice:xx}}, product2{} ...), what to do, you can convert this embedded JSON into our client's product class, Of course, this time you need to overload setvalue:forkey, processing "products" this key, wrapper it into the class we need

1234567891011 -(void) setValue:(id)value forKey:(NSString *)key{  if([key isEqualToString:@"products"])  {    for(NSMutableDictionary *productDict in value)    {      Prodcut *product = [[Product alloc] initWithDictionary:prodcutDict];      [self.products addObject:product];    }  }}

In Scenario 3, we need to capitalize the first letter of the name of the people in an array and put the new name into the new array, which is usually done by traversing the entire array and then extracting the name of each people, calling Capitalizedstring The new string is then added to the new array. With the KVC, there is a new approach:

1 [array valueForKeyPath:@"name.capitalizedString"]

We see Valueforkeypath, why use Valueforkeypath, not valueforkey, because Valueforkeypath can pass the relationship, for example, here is the name of each people property of the String Capitalizedstring property, and Valueforkey can not pass such a relationship, so for dict inside the dict, we can only use Valueforkeypath. Here we also see KVC for Array (set), do a special processing, not simple operation collection, but for these collection inside the elements to operate, the same KVC also provide more operations, such as @sum these for collection, Interested students can go to use the next.

Scene 4, when we execute nsarray *products = [People valueforkey:@ "products"], we want [people products], but people no such method, What will KVC bring to us?

    1. First will look for getprodcuts or products or isproducts, in this order to find, the first found on the return
    2. Then will go to countofproducts and either Objectinproductsatindex:or productsatindexes, if found, will find countofproducts and Enumeratorofproducts and Memberofproducts the 2 methods have been found, KVC will return to us an agent of the Nskeyvaluearray, for our subsequent operations (ADDPRODUCT and the like).
    3. If there is a variable called products , isproducts, or isproducts, KVC will use such a variable directly, if you feel that the direct use of such a variable is to destroy the encapsulation, you can prohibit such behavior occurs, overloading + accessinstancevariablesdirectly, returns No.

In short, Valueforkey, will bring us a proxy array, if we implement some methods, the appeal of these methods is only for Nsarray, for mutable collection, we also need to provide other methods of implementation.

Key Value Observing

Key Value observing, as the name implies is a observer mode for monitoring property changes, KVO and nsnotification have a lot of similar places, with AddObserver:forKeyPath:options : Context: Go to start observer, with REMOVEOBSERVER:FORKEYPATH:CONTEXT to stop Observer, callback is Observevalueforkeypath:ofobject: Change:context:.

1234567891011121314151617181920212223 - (void)removeObservation {    [self.object removeObserver:self                     forKeyPath:self.property];}- (void)addObservation {    [self.object addObserver:self forKeyPath:self.property                     options:0                     context:(__bridge void*)self];}- (void)observeValueForKeyPath:(NSString *)keyPath                      ofObject:(id)object                        change:(NSDictionary *)change                      context:(void *)context {  if ((__bridge id)context == self) {    // 只处理跟我们当前class的property更新  }  else {    [super observeValueForKeyPath:keyPath ofObject:object                           change:change context:context];  }}

For KVO, all we have to do is simply update our property data and don't need to be as concerned as nsnotificationcenter about whether someone is listening to your request, and if no one is listening, all addobserver, Removeobserver, callback are all things that you want to listen to the class of your property. Once a project, with Nsnotificationcenter Post notification in a network callback inside, but this time because the earliest Addobserver class was released, Then the generated Addobserver class, received the last observer to listen to the event, so caused the error, then the solution is to do a unique Addobserve key, not 2 times the Addobserver key is the same, But with the KVO, we can also use KVO to complete, when the Addoberver object remove, there will be no such callback is called.

KVO provides us with less code, and benefits than nsnotification, and does not need to modify the observed class, always observing your people doing things. But there's something wrong with KVO, 1. If there is no observer monitoring key path, RemoveObsever:forKeyPath:context: This key path, will be crash, unlike Nsnotificationcenter Removeobserver. 2. It's hard for you to find out who is listening to your property's changes, and it's more troublesome to find them. 3. For a complex and highly relevant class, it is best not to use KVO, delegate or notification way to be relatively concise.

Summary

Try to use KVC can greatly reduce the amount of our code, when encountered property, you can think of whether you can KVC to help me, whether you can use KVC to refactor the code, when the need to join the Observer mode, you can consider KVO, in the high-performance observer inside, KVO will give us a good help.

IOS KVC & KVO

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.