基本知識(shí)就不再介紹
-
一.說一下: KVC可以隨意修改一個(gè)對(duì)象的屬性或者成員變量(并且私有的也可以修改)
@property(nonatomic,copy) NSString *name;
它有三種表達(dá)方式(結(jié)果都一樣)
Person *person = [[Person alloc]init];
1.person.name = @"小紅";
2.[person setValue:@"小紅" forKey:@"name"];
3.[person setValue:@"小紅" forKey:@"_name"];
4.[person setValue:@"小紅" forKeyPath:@"_name"];
-
二.下面私有的定義變量又該如何
{ @private double _hight;//私有的變量,只有 }
設(shè)置值的方式應(yīng)該是
[person setValue:@12.3 forKey:@"_hight"];
而為什么不帶下劃線也一樣呢
[person setValue:@12.3 forKey:@"hight"];
原因:系統(tǒng)會(huì)查找hight相同的屬性时甚,如果找不到就會(huì)查找?guī)聞澗€的_hight
三.具體的說一下 forKey與forKeyPath的區(qū)別(通過給狗起名字來看看)建議以后都是用forKeyPath
聲明兩個(gè)類:Person和Dog類
在Person里面聲明兩個(gè)屬性
@property(nonatomic,copy) NSString *name;
@property(nonatomic,strong) Dog *dog;
在Dog里面聲明一個(gè)屬性
@property(nonatomic,copy) NSString *name;
//四者沒什么區(qū)別(取值直接用 [person valueForKeyPath:@" "])
//1.person.dog.name = @"汪汪";
//2.[person.dog setValue:@"汪汪" forKey:@"name"];
//3.[person.dog setValue:@"汪汪" forKeyPath:@"name"];
//4.[person setValue:@"汪汪" forKeyPath:@"dog.name"];
但是第4種如果這種寫就有區(qū)別了(forKey只尋找娶牌,person里面的屬性丸边,這里給dog設(shè)置名字是錯(cuò)誤的,path是路徑彻舰,需要一層一層的尋找)
[person setValue:@"汪汪" forKey:@"dog.name"];//錯(cuò)誤的寫法
- forKeyPath 包含了forKey的功能棋凳,以后使用keyPath就可以了
forKeyPath中可以利用.運(yùn)算符,就可以一層一層往下查找對(duì)象的屬性(再深也不怕鸿摇,一級(jí)一級(jí)往下用點(diǎn)屬性找)
區(qū)別總結(jié):forKey只尋找person里面的屬性,這里給dog設(shè)置名字是錯(cuò)誤的劈猿,path是路徑拙吉,需要一層一層的尋找
-
四.Cocoa的大招是kvc(下面說一下關(guān)于數(shù)組的用法,kvc很強(qiáng)大)
在人的屬性里面設(shè)置一個(gè)屬性
@property(nonatomic,strong) NSArray *books;
再寫一個(gè)Book類(聲明兩個(gè)屬性糙臼,再進(jìn)行一些屬性設(shè)置)@property(nonatomic,copy)NSString *name; @property(nonatomic,assign)double price; Person *person = [[Person alloc]init]; Book *book1 = [[Book alloc]init]; book1.name = @"迷茫"; book1.price = 21.5; Book *book2 = [[Book alloc]init]; book2.name = @"奮斗"; book2.price = 20.5; Book *book3 = [[Book alloc]init]; book3.name = @"努力"; book3.price = 24.5; Book *book4 = [[Book alloc]init]; book4.name = @"成功"; book4.price = 28.5; person.books = @[book1,book2,book3]; //需求把所有的書名放到一個(gè)數(shù)組里面 //1.for循環(huán)放值 NSMutableArray *array = [[NSMutableArray alloc]init]; for (Book *book in person.books) { [array addObject:book]; } NSLog(@"%@",array); //用kvc搞定 //@"books.name" 取出數(shù)組元素的每一個(gè)元素的name屬性的值庐镐,放到一個(gè)新的數(shù)組里面進(jìn)行返回 // NSArray *name = [person valueForKeyPath:@"books.name"]; NSArray *price = [person valueForKeyPath:@"books.price"]; //書本加起來一共多少錢?变逃?必逆?、 //1.種for循環(huán),定義數(shù)組名眉,去數(shù)組元素 double sum = 0; for (Book *book in person.books) { sum += book.price; } double sum = [[person valueForKeyPath:@"books.@sum.price"]doubleValue]; NSLog(@"%f",sum);