IOS開發之旅-KVC【索引值編碼】

來源:互聯網
上載者:User

標籤:

  在日常開發中,讀取修改對象的屬性值時,通常是點調用對應的屬性進行相關操作。另外一種方式是通過索引值編碼,簡稱KVC,在索引值編碼中主要使用以下方法

   /* Given a key that identifies an attribute or to-one relationship, return the attribute value or the related object. Given a key that 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 that 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 previously 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 it has more than one component (key path components are 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 be unable to get a keyed value using its default access mechanism, return the keyed value using some other mechanism. The default implementation of this method raises an NSUndefinedKeyException. You can override it to handle properties that are dynamically defined at run-time.*/

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

/* Given that an invocation of -setValue:forKey: would be unable to set the keyed value using its default mechanism, set the keyed value using some other mechanism. The default implementation of this method raises an NSUndefinedKeyException. You can override it to handle properties that are dynamically defined at run-time*/

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

/* Given that an invocation of -setValue:forKey: would be unable to set the keyed value because the type of the parameter of the corresponding accessor method is an NSNumber scalar type or NSValue structure type but the value is nil, set the keyed value using some other mechanism. The default implementation of this method raises an NSInvalidArgumentException. You 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 objects, set the keyed values. Dictionary entries whose values are 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 collections of to-many-related objects. Entries for which -valueForKey: returns nil have NSNull as their value in the returned dictionary.*/

- (NSDictionary *)dictionaryWithValuesForKeys:(NSArray *)keys;

下面以執行個體示範KVC,Person.h:

#import <Foundation/Foundation.h>@interface Person : NSObject-(id) initWithFirstName:(NSString *)firstName lastName:(NSString *)lastName age:(int)age;@property (nonatomic,copy) NSString *firstName;@property (nonatomic,copy) NSString *lastName;@property (nonatomic,strong) Person *father;@property 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;    }    return self;}//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:@18 forKey:@"age"];    }    else    {        [super setNilValueForKey:key];    }}//invoked by (setValue:forKey:) method,when it finds no property 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 property corresponding to a given value-(id)valueForUndefinedKey:(NSString *)key{    NSLog(@"%@ property not found",key);    return nil;}-(NSString *) description{    NSString *desc = [[NSString alloc] initWithFormat:@"firstName: %@, lastName:%@, age: %i", self.firstName,self.lastName,self.age];    return desc;}@end

測試代碼:

#import <Foundation/Foundation.h>#import "Person.h"int main(int argc, const char * argv[]) {    @autoreleasepool {        Person *person = [[Person alloc]initWithFirstName:@"xiao" lastName:@"long" age:26];        NSLog(@"%@",person);        //firstName: xiao, lastName:long, age: 26        NSLog(@"%@",[person valueForKey:@"firstName"]);        // xiao                [person setValue:@"quan" forKey:@"lastName"];        NSLog(@"%@",person.lastName);        //quan                        //middlenName 屬性不存在,則調用Person類的【-(void)setValue:(id)value forUndefinedKey:(NSString *)key】        [person setValue:@"pstune" forKey:@"middleName"];        //middleName property not found                //middlenName 屬性不存在,則調用Person類的【-(id)valueForUndefinedKey:(NSString *)key】        [person valueForUndefinedKey:@"middleName"];        //middleName property not found                //age 是實值型別,不能夠設定nil,所以調用Person類的【-(void)setNilValueForKey:(NSString *)key】        [person setValue:nil forKey:@"age"];        NSLog(@"%@",person);        //firstName: xiao, lastName:quan, age: 18                        Person *father = [[Person alloc]initWithFirstName:@"father" lastName:@"dad" age:50];        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: 50                NSDictionary *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總結:

  • 對於KVC,Cocoa會自動裝箱和開箱標量值(int,float,double)
  • -(id) valueForKey: (NSString*) key首先會尋找以參數命名的getter方法,如果不存在這樣的方法,將會繼續在對象內尋找名稱格式為_key或key的執行個體變數
  • -(id) valueForKey: (NSString*) key在Objective-C運行時中使用中繼資料開啟對象並進入其中尋找需要的資訊。

 

IOS開發之旅-KVC【索引值編碼】

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.