iOS Learning 8_KVC and dictionary turn models

Source: Internet
Author: User
Tags access properties

Key Value Coding is a standard component of cocoa, which allows us to access properties by name (key), which in some cases greatly simplifies the code. Can be called cocoa's big strokes.

For example, the following sample:

advantages of using KVCdo not use 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. }
using KVC

-(ID) TableView: (Nstableview *) Tableviewobjectvaluefortablecolumn: (ID) column row: (Nsinteger) row {    Childobject *child = [Childrenarray objectatindex:row];    return [child valueforkey:[column identifier];}

Obviously, a lot of code is simplified.

KVC OperationKVC Assignment Value

1 assigning values to the current object properties

-(void) SetValue: (ID) value Forkey: (NSString *) key;

2 Assigning values to properties of an object

-(void) SetValue: (ID) value Forkeypath: (NSString *) KeyPath;

3 handling keys that are not defined

-(void) SetValue: (ID) value Forundefinedkey: (NSString *) key

4 Dictionary to model: will be the same as the dictionary key name of the same class Proerty set on the Dict key corresponding value

-(void) Setvaluesforkeyswithdictionary: (Nsdictionary *) keyedvalues;

Note: The key in the dictionary is required and the object property is the same. is the primary OC data type: array/dictionary/boolean/data/number/string

KVC Value

1 getting the value of an object property

-(ID) Valueforkey: (NSString *) key;

2 Gets the value of the property of the object property

-(ID) Valueforkeypath: (NSString *) KeyPath;

Examples:

person * p = [[Person alloc]init]; Car *car = [[Car alloc]init];p. Car = car; [P setvalue:@ "Qhyuan" forkeypath:@ "name"]; [P setvalue:@ (forkey:@) "id"]; [P setvalue:@ "Baoshijie" forkeypath:@ "Car.brand"]; [P setvalue:@ "180000" forkeypath:@ "Car.price"]; NSLog (@ "KVC Person object----%@", p); NSString * name = [P valueforkey:@ "name"]; NSString * brand = [P valueforkeypath:@ "Car.brand"]; NSLog (@ "%@%@", name, brand);

Dictionary Turn ModelGeneral Situation


Model

Person.h

@interface Person:nsobject@property (nonatomic, copy) NSString * name; @property (nonatomic, assign) int age;-(Instancet ype) Initwithdict: (Nsdictionary *) dict;+ (instancetype) personwithdict: (Nsdictionary *) dict;+ (Nsarray *) person; @end
Person.m

@implementation person-(Instancetype) initwithdict: (nsdictionary *) dict{    if (self = [self init]) {//Use KVC dictionary to model so convenient 。 A large number of assignment codes are omitted [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

several keys in the dictionary are keyword in oc

Suppose the key age is replaced with an ID

will throw an exception:

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 handle keys that are not defined

-(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 includes some dictionaries or arrays that correspond to their own defined classes.


The person class has added a property of car type

@property (nonatomic, strong) car * car;

We just need to rewrite the following method

-(void) SetValue: (ID) value Forkey: (NSString *) key;

Workaround:

-(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) >) >"

)

It is a similar way to add a cars array instead of just adding the cars property.

iOS Learning 8_KVC and dictionary turn models

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.