------------筆記摘自黑馬IOS教程-----------
一:KVC
1)鍵路徑(key path)
比如,利用鍵路徑設置Student對象中Card對象的no
[student setValue:@"12345" forKeyPath:@"card.no"];
獲取Student對象中Card對象的no
[student valueForKeyPath:@"card.no"];
2)數組的整體操作
獲取Student中所有NSArray*books的name
NSArray *names = [student.books valueForKeyPath:@"name"];或者
NSArray *names = [student valueForKeyPath:@"books.name"];
3)在鍵路徑中,可以引用一些運算符來進行一些運算,例如獲取一組值的平均值、最小值、最大值或者總數
例如,計算Student中Book的總數
NSNumber *count = [student.books valueForKeyPath:@"@count"]; 或者
NSNumber *count = [student valueForKeyPath:@"books.@count"];
計算Student中所有Book的價錢(price)總和
NSNumber *sum = [student.books valueForKeyPath:@"@sum.price"];或者
NSNumber *sum = [student valueForKeyPath:@"[email protected]"];
找出Student中Book的所有不同價位(排除相同價位)
NSArray *prices = [student.books valueForKeyPath:@"@distinctUnionOfObjects.price"];
或者
NSArray *prices = [student valueForKeyPath:@"[email protected]"];
例如,同時獲取Student的age和name
NSArray *keys = [NSArray arrayWithObjects:@"name",@"age", nil];
NSDictionary *dict = [student dictionaryWithValuesForKeys:keys];
同時設置Student的age和name
NSArray *keys = [NSArray arrayWithObjects:@"name",@"age", nil];
NSArray *values = [NSArray arrayWithObjects:@"MJ",[NSNumber numberWithInt:16], nil];
NSDictionary *dict = [NSDictionary dictionaryWithObjects:values forKeys:keys];
[student setValuesForKeysWithDictionary:dict];
二、KVO (key value observer)鍵值觀察者 類似 鍵值改變的監聽器
步驟一:新增監聽對象PersonObser,並在.m實現如下方法
#pragma mark 當監聽的某個屬性發生改變時調用
/*
keyPath : 監聽的屬性名稱
object : 監聽的是哪個對象的屬性
change : 屬性發生的改變
context : 當初添加監聽器時傳入的參數
*/
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
//NSLog(@"%@-%@-%@", object, keyPath, context);
NSLog(@"change=%@", change);
}
步驟二:p的name屬性上加上監聽
Person *p = [[Person alloc] init];
p.age = 10;
p.name = @"jack";
PersonObserver *po = [[PersonObserver alloc] init];
int options = NSKeyValueObservingOptionOld
| NSKeyValueObservingOptionNew;
// 添加對象p的name屬性監聽器(observer)
[p addObserver:po forKeyPath:@"name" options:options context:@"432432"];
p.name = @"Mike";
// 刪除監聽器
[p removeObserver:po forKeyPath:@"name"];