//基本的KVC(Key,Value,Coding)基本概念
Person *person = [[Person alloc] init];
//下面會先判斷getter/setter方法是否存在 如果存在先會調用getter/setter方法
[person setValue:@"1" forKey:@"compatibility"];
//valueForKey獲取對象的數值 如果存儲的是基本數據類型 必須先轉換成對象 然後對象轉換基本數據類型
NSNumber *number = [person valueForKey:@"compatibility"];
//設置對象
[person setValue:[Car new] forKey:@"car"];
//設置當前Person裏面的cat對象的屬性
[person setValue:[NSNumber numberWithInt:1] forKeyPath:@"car.status"];
//獲取
NSNumber *num1 = [person valueForKeyPath:@"car.status"];
//創建第一本書
book *book1 = [[book alloc] init];
[book1 setValue:@"三國演義" forKey:@"name"];
[book1 setValue:[NSNumber numberWithInt:124] forKey:@"price"];
//創建第二本書
book *book2 = [[book alloc] init];
[book2 setValue:@"三國演義" forKey:@"name"];
[book2 setValue:[NSNumber numberWithInt:125] forKey:@"price"];
//創建包含書籍對象
NSArray *array = [[NSArray alloc] initWithObjects:book1,book2,nil];
//設置屬性
[person setValue:array forKey:@"array"];
//KVC可以做一些簡單的運算 存儲的數量
NSLog(@"%@",[person valueForKeyPath:@"array.@count"]);
//總和
NSLog(@"%@",[person valueForKeyPath:@"[email protected]"]);
//平均
NSLog(@"%@",[person valueForKeyPath:@"[email protected]"]);
//最大
NSLog(@"%@",[person valueForKeyPath:@"[email protected]"]);
//最小
NSLog(@"%@",[person valueForKeyPath:@"[email protected]"]);
OC-簡單介紹KVC和簡單的使用!
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.