KVC非常的靈活,它可以做許多你想不到的事情 .
教程不如例子能看懂,我整理后出了demo在這里
代碼有兩個demo, 第一個demo是講KVC解析, 本文內(nèi)容在第二個demo方法里
NSKeyValueCoding
這種統(tǒng)一的直接通過字符串存取ObjC中對象的成員屬性的接口缎玫,可以實現(xiàn)由外部腳本控件程序執(zhí)行或者獲取程序執(zhí)行信息腔丧。
通過KVC存取二進制庫中的私有成員也比較實用歌溉。
也是使用KVO和CoreData的基礎(chǔ)利赋。
先看這個Class
@interface Teacher : NSObject
{
@private
NSNumber *age ;
}
@property (nonatomic,copy,readonly) NSString *name ;
@property (nonatomic,strong) Student *student ;
- (instancetype)initWithStudent:(Student *)student ;
- (void)logAge ;
@end
看到這個類有私有變量,和只讀變量, 如果用一般的setter
和getter
, 在類外部是者訪問到私有變量的, 不能重寫只讀變量,那是不是就拿它沒辦法了呢?
然而KVC就是這么神奇
KVC精華總結(jié)
1.修改只讀readonly
變量
readonly只讀. 是不能直接賦值的, 但是KVC可以 .
**e.g. **
如果想這樣~~teacher1.name = @"張三" ~~ 是不行的,因為name是只讀變量. 可以通過KVC
[teacher1 setValue:@"Teacher_teason" forKey:@"name"] ;
2.修改私有private
變量
KVC可以修改一個對象的屬性和變量, 即使它是私有的.
e.g.
teacher1.age = 24 ;肯定不能用了
[teacher1 setValue:@24 forKey:@"age"] ;
如果變量名字為"_age"
那么用age和
_age`都可以, KVC內(nèi)部邏輯是先查找age在查找_age
3.通過運算符層次查找對象的屬性
Student *student1 = [[Student alloc] initWithName:@"Student_Teason" bookList:mutableList] ;
Teacher *teacher1 = [[Teacher alloc] initWithStudent:student1] ;
NSLog(@"All book name : %@",[teacher1 valueForKeyPath:@"student.bookList.name"]) ;
NSLog(@"All book name : %@",[student1 valueForKeyPath:@"bookList.name"]) ;```
這兩個打印的結(jié)果是一樣的 .通過keyPath直接訪問屬性.
> **All book name : (**
** book10,**
** book11,**
** book12,**
** book13,**
** book14,**
** book15,**
** book16,**
** book17,**
** book18,**
** book19,**
** book20**
**)**
4.獲取數(shù)組
for (Book *book in [student1 valueForKey:@"bookList"]) {
// [student1 valueForKey:@"bookList"]返回一個數(shù)組
NSLog(@"bookName : %@ \t price : %f",book.name,book.price) ;
}```
5.對屬性進行數(shù)學(xué)運算
NSLog(@"sum of book price : %@",[student1 valueForKeyPath:@"bookList.@sum.price"]) ;
NSLog(@"avg of book price : %@",[student1 valueForKeyPath:@"bookList.@avg.price"]) ;```
so that's it.
demo[Github地址](https://github.com/Akateason/Demo_KVC)
如果覺得豁然開朗戳表,可以去demo點個Star戈抄,你的舉手之勞狡相,對我的鼓勵是巨大的。
> 相關(guān)
詳解KVC1http://www.reibang.com/p/ddff26a58172
詳解KVC2http://www.reibang.com/p/0a2d5ff328d2
http://www.bubuko.com/infodetail-919348.html