IOS基础学习笔记三:KVC和KVO数组的整体操作

------------笔记摘自黑马IOS教程-----------

一:KVC

1)键路径(key path)

比如,利用键路径设置Student对象中Card对象的no

[student setValue:@"12345" forKeyPath:@"card.no"];

获取Student对象中Card对象的no

[student valueForKeyPath:@"card.no"];

2)数组的整体操作

获取Student中所有NSArray*booksname

NSArray *names = [student.books valueForKeyPath:@"name"];或者

NSArray *names = [student valueForKeyPath:@"books.name"];


3)在键路径中,可以引用一些运算符来进行一些运算,例如获取一组值的均值、最小值、最大值或者总数

例如,计算StudentBook的总数

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]"];

找出StudentBook的所有不同价位(排除相同价位)

NSArray *prices = [student.books valueForKeyPath:@"@distinctUnionOfObjects.price"];

或者

NSArray *prices = [student valueForKeyPath:@"[email protected]"];


4)对对象进行批量更改

例如,同时获取Studentagename

NSArray *keys = [NSArray arrayWithObjects:@"name",@"age", nil];

NSDictionary *dict = [student dictionaryWithValuesForKeys:keys];


同时设置Studentagename

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"];



你可能感兴趣的:(IOS基础)