Ios learns 8_KVC and dictionary-to-model, ios8_kvc dictionary Model

Source: Internet
Author: User

Ios learns 8_KVC and dictionary-to-model, ios8_kvc dictionary Model

Key Value Coding is a standard component of cocoa. It allows us to access attributes by name (key). In some cases, the code is greatly simplified, which can be called the big trick of cocoa.

Example:

Advantages of using KVC

- (id)tableView:(NSTableView *)tableviewobjectValueForTableColumn:(id)column row:(NSInteger)row {    ChildObject *child = [childrenArray objectAtIndex:row];    if ([[column identifier] isEqualToString:@"name"]) {       return [child name];    }   if ([[column identifier] isEqualToString:@"age"]) {       return [child age];    }   if ([[column identifier] isEqualToString:@"favoriteColor"]) {          return [child favoriteColor];    }    // And so on. }
Use KVC

- (id)tableView:(NSTableView *)tableviewobjectValueForTableColumn:(id)column row:(NSInteger)row {    ChildObject *child = [childrenArray objectAtIndex:row];    return [child valueForKey:[column identifier]];}

Obviously, it simplifies a lot of code.

KVC assignment

1. assign a value to the attribute of the current object.

- (void)setValue:(id)value forKey:(NSString *)key;

2. assign values to attributes of an object.

- (void)setValue:(id)value forKeyPath:(NSString *)keyPath;

3. Process undefined keys

- (void) setValue:(id)value forUndefinedKey:(NSString *)key

4. dictionary-to-model conversion: class proerty with the same name as the dictionary key will be set to the value corresponding to the key in dict.

- (void)setValuesForKeysWithDictionary:(NSDictionary *)keyedValues;

Note: The keys and object attributes in the Dictionary must be the same. They are all basic OC Data types: Array/Dictionary/Boolean/Data/Number/String.

KVC Value

1. Get the object property value

- (id)valueForKey:(NSString *)key;

2. Obtain the property value of an object property.

- (id)valueForKeyPath:(NSString *)keyPath;

Example:

Person * p = [[Person alloc] init]; Car * car = [[Car alloc] init]; p. car = car; [p setValue: @ "qhyuan" forKeyPath: @ "name"]; [p setValue: @ (20) forKey: @ "id"]; [p setValue: @ "baoshijie" forKeyPath: @ "car. brand "]; [p setValue: @" 180000 "forKeyPath: @" car. price "]; NSLog (@" person object of the kvc principal value ---- % @ ", p); NSString * name = [p valueForKey: @" name "]; NSString * brand = [p valueForKeyPath: @ "car. brand "]; NSLog (@" % @ ", name, brand );

General Situation of dictionary-to-model conversion


Model

Person. h

@interface Person : NSObject@property (nonatomic, copy) NSString * name;@property (nonatomic, assign) int age;- (instancetype) initWithDict:(NSDictionary *) dict;+ (instancetype) personWithDict:(NSDictionary *) dict;+ (NSArray *) person;@end
Person. m

@ Implementation Person-(instancetype) initWithDict :( NSDictionary *) dict {if (self = [self init]) {// It is so convenient to use the KVC dictionary to convert models, saves a lot of value assignment code [self setValuesForKeysWithDictionary: dict]; // self. name = dict [@ "name"]; // self. age = [dict [@ "age"] integerValue];} return self;} + (instancetype) personWithDict :( NSDictionary *) dict {return [self alloc] initWithDict: dict] ;}+ (NSArray *) person {NSMutableArray * mutablePersons = [NSMutableArray array]; NSString * path = [[NSBundle mainBundle] pathForResource: @ "persons. plist "ofType: nil]; NSArray * persons = [[NSArray alloc] initWithContentsOfFile: path]; for (NSDictionary * person in persons) {[mutablePersons addObject: [self personWithDict: person];} return mutablePersons;}-(NSString *) description {NSString * desc = [NSString stringWithFormat: @ "<% p :( % @, % d)> ", self, self. name, self. age]; return desc;} @ end

Multiple keys in the dictionary are keywords in OC.

If you replace the key age with the id

An exception is thrown:

* ** Terminating app due to uncaught exception 'nsunknownkeyexception', reason: '[<Person 0x8c419a0> setValue: forUndefinedKey:]: this class isnot key value coding-compliant for the key id.

Override the following method to process undefined keys.

- (void)setValue:(id)value forUndefinedKey:(NSString *)key;

Solution:

- (void) setValue:(id)value forUndefinedKey:(NSString *)key{    if([key isEqualToString:@"id"])        key = @"age";    [super setValue:value forKey:key];}

The dictionary also contains some dictionaries or arrays corresponding to custom classes.


The Person class adds a property of the Car type.

@property (nonatomic, strong) Car * car;

We only need to override the following method

- (void)setValue:(id)value forKey:(NSString *)key;

Solution:

- (void)setValue:(id)value forKey:(NSString *)key{    if([key isEqualToString:@"cars"])    {        Car *car = [Car carWithDict:(NSDictionary *)value];        self.car = car;    }    else        [super setValue:value forKey:key];}
Print results

Dictionary to model [5525: 60b] (

"<Person :( zhangsan, 20, <Car :( benchi, 180000)> ",

"<Person :( lisi, 22, <Car :( baoma, 180000)> ",

"<Person :( wangwu, 24, <Car :( aodi, 180000)>"

)

If the Cars array is added instead of the Cars attribute, It is similar.

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.