iOS development Tour-KVC "key value encoding"

Source: Internet
Author: User
Tags scalar

In daily development, when you read a property value that modifies an object, it is usually a point to invoke the corresponding property to do something about it. Another way is to use key-value coding, referred to as KVC, in key-value coding mainly uses the following methods

/* Given A key, identifies an attribute or to-one relationship, return the attribute value or the related object. Given a key, identifies a to-many relationship, return an immutable array or an immutable set that contains all of the Related objects.*/

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

/* Given a value and a key, identifies an attribute, set the value of the attribute. Given an object and a key that identifies a to-one relationship, relate the object to the receiver, unrelating the Previou Sly related Object if there was one. Given a Collection object and a key that identifies a to-many relationship, relate the objects contained in the collection To the receiver, unrelating previously related objects if there were any.*/

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

/* key-path-taking variants of like-named methods. The default implementation of each parses the key path enough to determine whether or not is it has more than one component ( Key path components is separated by periods). If So,-valueforkey:is invoked with the first key path component as the argument, and the method being invoked is invoked Recursively on the result, with the remainder of the key path passed as an argument. If not, the like-named non-key-path-taking method is invoked.*/

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

/* Given that an invocation of-valueforkey:would is unable to get a keyed value using the its default access mechanism, Retu RN The keyed value using some other mechanism. The default implementation of this method raises an nsundefinedkeyexception. can override it to handle properties that is dynamically defined at run-time.*/

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

/* Given that an invocation of-setvalue:forkey:would is unable to set the keyed value using its default mechanism, set T He keyed value using some other mechanism. The default implementation of this method raises an nsundefinedkeyexception. can override it to handle properties that is dynamically defined at run-time*/

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

/* Given that an invocation of-setvalue:forkey:would is unable to set the keyed value because the type of the parameter of the corresponding accessor method is a nsnumber scalar type or nsvalue structure type but the value is nil, set the KE Yed value using some other mechanism. The default implementation of this method raises an nsinvalidargumentexception. can override it to map nil values to something meaningful in the context of your application.*/

-(void) Setnilvalueforkey: (NSString *) key;

/* Given A dictionary containing keyed attribute values, to-one-related objects, and/or collections of to-many-related obj ECTS, set the keyed values. Dictionary entries whose values is NSNull result In-setvalue:nil forkey:key messages being sent to the receiver.*/

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

/* Given An array of keys, return a dictionary containing the keyed attribute values, to-one-related objects, and/or Colle Ctions of To-many-related objects. Entries for Which-valueforkey:returns Nil has NSNull as their value in the returned dictionary.*/

-(Nsdictionary *) Dictionarywithvaluesforkeys: (Nsarray *) keys;

The following example shows Kvc,person.h:

#import <Foundation/Foundation.h>@interface  person:nsobject-(ID) Initwithfirstname: (NSString *) firstName lastName: (NSString *) LastName Age: (int**  *int age ; @end

PERSON.M:

#import "Person.h"@implementation Person-(ID) Initwithfirstname: (NSString *) firstName lastName: (NSString *) LastName Age: (int) age{if(self =[Super Init]) {Self.firstname=FirstName; Self.lastname=LastName; Self.age=Age ; }    returnSelf ;}//invoked by (Setvalue:forkey:) Method,when It's given a nil value for a scalar value (such as int or float)-(void) Setnilvalueforkey: (NSString *) key{if([Key isequaltostring:@" Age"]) {[Self setvalue:@ -Forkey:@" Age"]; }    Else{[Super Setnilvalueforkey:key]; }}//invoked by (Setvalue:forkey:) Method,when it finds No. corresponding to a given value-(void) SetValue: (ID) value Forundefinedkey: (NSString *) key{NSLog (@"%@ Property not found", key);}//invoked by (Valueforkey:) Method,when it finds No. corresponding to a given value-(ID) Valueforundefinedkey: (NSString *) key{NSLog (@"%@ Property not found", key); returnNil;}-(NSString *) description{NSString*desc = [[NSString alloc] Initwithformat:@"firstName:%@, lastname:%@, age:%i", Self.firstname,self.lastname,self.age]; returndesc;}@end

Test code:

#import<Foundation/Foundation.h>#import "Person.h"intMainintargcConst Char*argv[]) {@autoreleasepool { person*person = [Person Alloc]initwithfirstname:@"Xiao"LastName:@"Long"Age -]; NSLog (@"%@", person); //Firstname:xiao, Lastname:long, age:26NSLog (@"%@", [Person Valueforkey:@"FirstName"]); //Xiao[Person SetValue:@"Quan"Forkey:@"LastName"]; NSLog (@"%@", Person.lastname); //Quan//Middlenname property does not exist, call the "-(void) SetValue of the Person class: (ID) value Forundefinedkey: (NSString *) key"[Person SetValue:@"Pstune"Forkey:@"MiddleName"]; //MiddleName Property not found//The Middlenname property does not exist, then the "-(ID) Valueforundefinedkey: (NSString *) key" of the person class is called[Person Valueforundefinedkey:@"MiddleName"]; //MiddleName Property not found//Age is a value type and cannot be set to nil, so call the "-(void) Setnilvalueforkey of the Person class: (NSString *) key"[Person Setvalue:nil Forkey:@" Age"]; NSLog (@"%@", person); //Firstname:xiao, Lastname:quan, age:18 Person*father = [Person Alloc]initwithfirstname:@"Father"LastName:@"dad"Age -]; Person.father=father; NSLog (@"father FirstName:%@", [Person Valueforkeypath:@"Father.firstname"]); //Father Firstname:father[Person SetValue:@"Quan"Forkeypath:@"Father.lastname"]; NSLog (@"%@", father); //Firstname:father, Lastname:quan, age:50nsdictionary*propertydic = [Person dictionarywithvaluesforkeys:@[@"FirstName",@"LastName"]]; NSLog (@"%@", Propertydic); /*{firstName = Xiao;         LastName = Quan; }         */[Person setvaluesforkeyswithdictionary:@{@"FirstName":@"Pstune",@"LastName":@"Web"}]; NSLog (@"%@", person); //Firstname:pstune, Lastname:web, age:18    }    return 0;}

KVC Summary:

    • For Kvc,cocoa automatic boxing and unpacking scalar values (int,float,double)
    • -(ID) Valueforkey: (nsstring*) Key first looks up the getter method named after the parameter, and if no such method exists, it will continue to look for an instance variable with the name format _key or key in the object
    • -(ID) Valueforkey: (nsstring*) key opens the object with metadata in the OBJECTIVE-C runtime and enters it to find the required information.

iOS development Tour-KVC "key value encoding"

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.