KVO
全称KeyValueObserving
,是苹果提供的一套事件通知机制
。允许对象监听
另一个对象特定属性的改变,并在改变时接收到事件
。由于KVO
的实现机制,所以对属性才会发生作用,一般继承自NSObject
的对象都默认支持KVO
。
KVO
和NSNotificationCenter
都是iOS中观察者
模式的一种实现。区别在于,相对于被观察者
和观察者
之间的关系,KVO
是一对一
的,而不一对多的。KVO
对被监听对象无侵入性,不需要修改其内部代码即可实现监听。
KVO
可以监听单
个属性的变化,也可以监听集合
对象的变化。通过KVC
的mutableArrayValueForKey:
等方法获得代理对象
,当代理对象的内部对象发生改变时,会回调KVO
监听的方法。集合对象包含NSArray
和NSSet
。
KVO的使用
1、基本使用
@interface LGPerson : NSObject
@property (nonatomic, copy) NSString *name;
@property (nonatomic, copy) NSString *nick;
@property (nonatomic, copy) NSString *downloadProgress;
@property (nonatomic, assign) double writtenData;
@property (nonatomic, assign) double totalData;
@property (nonatomic, strong) NSMutableArray *dateArray;
@property (nonatomic, strong) LGStudent *st;
@end
static void *PersonNickContext = &PersonNickContext;
@interface LGViewController ()
@property (nonatomic, strong) LGPerson *person;
@property (nonatomic, strong) LGStudent *student;
@end
@interface LGViewController ()
@property (nonatomic, strong) LGPerson *person;
@property (nonatomic, strong) LGStudent *student;
@end
@implementation LGViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.person = [LGPerson new];
// 1: context : 上下文
[self.person addObserver:self forKeyPath:@"nick" options:NSKeyValueObservingOptionNew context:NULL];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
self.person.nick = [NSString stringWithFormat:@"%@+",self.person.nick];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
// 性能 + 代码可读性
NSLog(@"%@",change);
}
- (void)dealloc{
[self.person removeObserver: