简单说一嘴KVO

2017-03-26  本文已影响64人  mkb2

就说说手动调用和自动调用

KVO的调用很简单

 1.对一个对象添加观察者
    [p addObserver:self(self是控制器)
        forKeyPath:NSStringFromSelector(@selector(address))
           options:NSKeyValueObservingOptionNew
           context:nil];

 2.实现接收变化的方法
- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary<NSKeyValueChangeKey,id> *)change
                       context:(void *)context{
    NSLog(@"key path = %@",keyPath);
}

3.使用KVC方法,然后就能调用KVO了
    [p setValue:@"nfadfddsfaf" forKey:NSStringFromSelector(@selector(address))];
    [document setValue:@"Savings" forKeyPath:@"p.address"];
    [p setAddress:@"白山"];


什么是手动调用?

当我们按照上边的去监听了,每一次address属性发生变化了,都可以自动发送一个通知,通知是KVO的本质,但是当address 赋值了,但是很刚才一样,都是“白山”,那么发送通知白费了,多余,所有才有了手动出发KVO这个说法;
说白了,就是我想手动出发KVO,如何写?

刚才监听了WXPerson类,以他为例,就是动态生成了一个NotifyWXPerson(类名称忘了,但是差不多)一个衍生类,然后重写了新类的- setAddress:(NSString *)address方法,然后写了这个代码

//手动触发
- (void)setAddress:(NSString *)address{
        [self willChangeValueForKey:NSStringFromSelector(@selector(address))];
        _address = address;
       [self didChangeValueForKey:NSStringFromSelector(@selector(address))];
}

//排除相同的干扰,免去瞎发多余无用的通知
- (void)setAddress:(NSString *)address{
      if([_address isEquel:address]) return;
        [self willChangeValueForKey:NSStringFromSelector(@selector(address))];
        _address = address;
       [self didChangeValueForKey:NSStringFromSelector(@selector(address))];
}


只要我们做了这些:
1.我们添加了对这个属性的观察
2.我们实现了“接收变化的方法”
3.KVC设置值
那么手动发送通知就可以实现~

问题是,如果使用了KVC赋值,那么“接收变化的方法”会调用两次

文档中

Manual and automatic notifications are not mutually exclusive
手动出发通知和自动出发通知,互不排斥,就是可以同时有

如何关闭系统的?

+ (BOOL)automaticallyNotifiesObserversForKey:(NSString *)key{
    if ([key isEqualToString:NSStringFromSelector(@selector(address))]) {
        return NO;
    }
    return [super automaticallyNotifiesObserversForKey:key];
}

如果我想在address改变的时候,触发其他的属性通知咋整?

@interface WXPerson : WXAnimamal
/** name */
@property(copy,nonatomic)  NSString *name;
/** add */
@property(copy,nonatomic)  NSString *address;
@end

在外边我们做了监听name的操作,当address发送变化,也要触发name的操作,name变成了"哈哈哈"

- (void)setAddress:(NSString *)address{
        [self willChangeValueForKey:NSStringFromSelector(@selector(address))];
        [self willChangeValueForKey:NSStringFromSelector(@selector(name))];
        _address = address;
        _name = @"哈哈";
        [self didChangeValueForKey:NSStringFromSelector(@selector(name))];
       [self didChangeValueForKey:NSStringFromSelector(@selector(address))];
}

为啥说这个?

因为看到AFNetworking和SDWebImage经常使用手动出发KVO,过去不太懂,慢慢看到了,就记下来.

KVO文档

上一篇下一篇

猜你喜欢

热点阅读