KVC非常的靈活,它可以做許多你想不到的事情 .
教程不如例子能看懂,我整理后出了demo在這里
代碼有兩個(gè)demo, 第一個(gè)demo是講KVC解析, 本文內(nèi)容在第二個(gè)demo方法里
NSKeyValueCoding
這種統(tǒng)一的直接通過字符串存取ObjC中對(duì)象的成員屬性的接口,可以實(shí)現(xiàn)由外部腳本控件程序執(zhí)行或者獲取程序執(zhí)行信息。
通過KVC存取二進(jìn)制庫中的私有成員也比較實(shí)用。
也是使用KVO和CoreData的基礎(chǔ)。
先看這個(gè)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
看到這個(gè)類有私有變量,和只讀變量, 如果用一般的setter和getter, 在類外部是者訪問到私有變量的, 不能重寫只讀變量,那是不是就拿它沒辦法了呢?
然而KVC就是這么神奇
KVC精華總結(jié)
1.修改只讀readonly變量
readonly只讀. 是不能直接賦值的, 但是KVC可以 .
**e.g. **
如果想這樣~~teacher1.name = @"張三" ~~ 是不行的,因?yàn)閚ame是只讀變量. 可以通過KVC
[teacher1 setValue:@"Teacher_teason" forKey:@"name"] ;
2.修改私有private變量
KVC可以修改一個(gè)對(duì)象的屬性和變量, 即使它是私有的.
e.g.
teacher1.age = 24 ;肯定不能用了
[teacher1 setValue:@24 forKey:@"age"] ;
如果變量名字為"_age"那么用age和_age`都可以, KVC內(nèi)部邏輯是先查找age在查找_age
3.通過運(yùn)算符層次查找對(duì)象的屬性
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"]) ;```
這兩個(gè)打印的結(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"]返回一個(gè)數(shù)組
NSLog(@"bookName : %@ \t price : %f",book.name,book.price) ;
}```
5.對(duì)屬性進(jìn)行數(shù)學(xué)運(yùn)算
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點(diǎn)個(gè)Star,你的舉手之勞,對(duì)我的鼓勵(lì)是巨大的。
> 相關(guān)
詳解KVC1http://m.itdecent.cn/p/ddff26a58172
詳解KVC2http://m.itdecent.cn/p/0a2d5ff328d2
http://www.bubuko.com/infodetail-919348.html