IOS開發-KVC

來源:互聯網
上載者:User

標籤:style   blog   http   io   color   os   ar   使用   for   

1. 什麼是kvc

kvc--key-value coding,健值編碼

可以通過key直接存取對象屬性的value的方法

 

2.使用情境

kvc主要是為了讓代碼變的更簡介明了

用的比較多的是在後台資料解析,還有訪問一些沒有setter,getter方法的屬性

 

3.代碼解析:

定義都在NSKeyValueCoding.h中

主要兩個方法:

//key為當前類的屬性名稱- (id)valueForKey:(NSString *)key;  //當類沒有名為key的屬性時會調用拋出異常,可以複寫valueForUndefinedKey:方法,作處理- (void)setValue:(id)value forKey:(NSString *)key;//當類沒有名為key的屬性時會調用拋出異常,可以複寫- (void)setValue:(id)value forUndefinedKey:(NSString *)key:方法,作處理//keyPath 為訪問屬性的路徑,比如:@"person.name",person是當前類的屬性,name是person類的一個屬性名稱- (id)valueForKeyPath:(NSString *)keyPath;- (void)setValue:(NSValue *)value forKeyPath:(NSString *)keyPath;

 

異常處理

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

 

代碼舉例:

@interface ViewController () @property (nonatomic, weak) NSString *viewString;@end@implementation ViewController- (void)viewDidLoad {    [super viewDidLoad];    NSLog(@"----[%@]",[self valueForKey:@"viewString"]);    NSLog(@"----[%@]",[self valueForKey:@"viewArray"]);     [self setValue:@"testForViewString" forKey:@"viewString"];    [self setValue:@"1" forKey:@"viewArray"]; }- (void)setValue:(id)value forUndefinedKey:(NSString *)key {    NSLog(@"【warning】!!!!!!---Undefined--key[%@]--!!!!!!",key);}- (id)valueForUndefinedKey:(NSString *)key {    if ([key isEqualToString:@"viewArray"]) {        return @"aaaa";    }    else {        return [super valueForUndefinedKey:key];    }}

 

實現原理

參考 http://www.tuicool.com/articles/M7vQRj

感謝這篇文章,寫的很詳細

但有個疑問:

雖然說這幾個方法一般不會去調用或者用到,但是我嘗試了一下,系統並沒有調用這些方法,而是直接走到了

- (id)valueForUndefinedKey:(NSString *)key

 

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.