KVO 与KVC

  • KVC
    KVC是KeyValueCoding的简称,它是一种可以直接通过字符串的名字(key)来访问类属性的机制。而不是通过调用Setter、Getter方法访问。

Person.h

@interface Person : NSObject

@property (strong, nonatomic) NSString *name;
@property (assign, nonatomic) NSInteger age;
@property (strong, nonatomic) NSString *code;
@property (assign, nonatomic) double height;

@end

main.m

NSDictionary *dic = @{@"name" : @"admin",
@"age"  : @13, @"code" : @"111222333",
@"height" : @12.4};

Person *person = [[Person alloc] init];
person.name = @"person name";

    //KVC
[person setValue:@"KVC name" forKey:@"name"];
[person setValue:@12 forKey:@"age"];
[person setValue:@"112233" forKey:@"code"];
[person setValue:@15.9 forKey:@"height"];

   // 利用KVC将json转Model
for (NSString *key in dic) {

  [person setValue:dic[key] forKey:key];

 }
   // 一次性转
[person setValuesForKeysWithDictionary:dic];


  • KVO
    KVO,即:Key-Value Observing,它提供一种机制,当指定的对象的属性被修改后,则对象就会接受到通知。简单的说就是每次指定的被观察的对象的属性被修改后,KVO就会自动通知相应的观察者了。

设置监听者

- (void)setStock:(Stock *)stock {

    _stock = stock;
    // 1. 设置监听(注册监听)
    // 参数:监听者,监听值,监听选项,上下文
    [_stock addObserver:self forKeyPath:@"price" options:NSKeyValueObservingOptionNew context:nil];
}

处理监听

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {

    NSLog(@"keypath : %@", keyPath);
    NSLog(@"object : %@", object);
    NSLog(@"change : %@", change);
    // 2. 处理监听(当股票涨到40以上后,调用sell方法卖出)
    NSNumber *newPriceNumber = change[@"new"];
    if ([newPriceNumber intValue] >= 40) {
          [self sell];
    }
}
change字典与添加观察者中的参数相对应

NSKeyValueObservingOptions      change
-------------------------------------------
NSKeyValueObservingOptionNew        @{kind = ;new = ;}

NSKeyValueObservingOptionOld        @{kind = ;old = ;}

NSKeyValueObservingOptionInitial    @{kind = ;}

NSKeyValueObservingOptionPrior      @{kind = 1; 
notificationIsPrior = 1;} @{kind = 1;} @{kind = 1;notificationIsPrior = 1;}

移除监听

- (void)dealloc {
    // 3. 移除监听
    [_stock removeObserver:self forKeyPath:@"price"];
}

你可能感兴趣的:(ios项目)