IOS基礎学習ノート3:KVCとKVO配列の全体操作

2738 ワード

---------------------------------

一:KVC


1)キーパス(key path)


たとえば、StudentオブジェクトのCardオブジェクトのnoをキーパスで設定する
[student setValue:@"12345" forKeyPath:@"card.no"];
StudioオブジェクトのCardオブジェクトのnoを取得
[student valueForKeyPath:@"card.no"];


2)配列全体の操作
StudioのNSArray*booksの名前をすべて取得
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]"];
4)オブジェクトの一括変更
例えば、Studentのageとnameを同時に取得する
NSArray *keys = [NSArray arrayWithObjects:@"name",@"age", nil];
NSDictionary *dict = [student dictionaryWithValuesForKeys:keys];
Studioの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)キー値観察者類似キー値変化のリスナー


ステップ1:リスニング対象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);
}

ステップ2: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"];