關於KVC索引值編碼

來源:互聯網
上載者:User

標籤:

轉載自http://www.tuicool.com/articles/2aYfy2

Key-value coding,它是一種使用字串標識符,間接訪問對象屬性的機制,而不是直接調用getter 和 setter方法。通常我們使用valueForKey 來替代getter 方法,setValue:forKey來代替setter方法。

首先來看一看KVC與setter,getter方法賦值的區別

Persion *person =  [ [Person alloc] init ];//不使用KVCperson.name = @"hufeng" ;//使用KVC的寫法[person  setValue:@"hufeng" forKey:@"name"];

下面我們寫個複雜點的:我們有一個人 這個人有一個手機 這個手機類 有一個電池類 我們要擷取這個電池類。

//使用屬性Persion *person =  [ [Person alloc] init ];Phone *phone = person.phone;Battery *battery = phone.battery;
//使用KVC
Battery *battery = [person valueForKeyPath: @"phone.battery" ];

注意- valueForKeyPath 裡面的值是區分大小寫,你如果寫出Phone.Battery 是不行的。

KVC 最常用的還是在序列化和反序列話對象。我們經常需要把json字串還原序列化成我們想要的對象 下面是一個例子 將字典用NSKeyedArchiver 序列化成對象。

- (id)initWithDictionary:(NSDictionary *)dictionary {    self = [self init];    if (self){        [self setValuesForKeysWithDictionary:dictionary];    }    return self;}

 

關於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.