KVO
添加
addObserver:forKeyPath: options:context:
- (void)addObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath options:(NSKeyValueObservingOptions)options context:(nullable void *)context;
- observer - 监听器
- keyPath - key
- options
typedef NS_OPTIONS(NSUInteger, NSKeyValueObservingOptions) {
NSKeyValueObservingOptionNew = 0x01,
NSKeyValueObservingOptionOld = 0x02,
NSKeyValueObservingOptionInitial = 0x04,
NSKeyValueObservingOptionPrior = 0x08
};
- context - Arbitrary data that is passed to
observerin [observeValueForKeyPath:ofObject:change:context:]
移除
- (void)removeObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath
context:(nullable void *)context
- (void)removeObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath
监听方法
- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary *)change
context:(nullable void *)context;
应用
@interface NSPerson : NSObject
@property(nonatomic,assign)int age;
@property(nonatomic,assign)double height;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.person = [NSPerson new];
self.person.age = 10;
self.person.height = 180;
NSKeyValueObservingOptions options = NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld;
[self.person addObserver:self forKeyPath:@"age" options:options context:nil];
[self.person addObserver:self forKeyPath:@"height" options:options context:nil];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
NSLog(@"keyPath:%@",keyPath);
NSLog(@"object:%s",object_getClassName(object));
NSLog(@"change:%@",change);
NSLog(@"context:%@",context);
}
- (void)dealloc
{
[self.person removeObserver:self forKeyPath:@"age"];
[self.person removeObserver:self forKeyPath:@"height"];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
self.person.age = 20;
self.person.height = 182;
}
@end
log
2020-06-27 22:56:25.704268+0800 KVO[61945:2417667] keyPath:age
2020-06-27 22:56:25.704641+0800 KVO[61945:2417667] object:NSKVONotifying_NSPerson
2020-06-27 22:56:25.705091+0800 KVO[61945:2417667] change:{
kind = 1;
new = 20;
old = 10;
}
2020-06-27 22:56:25.705399+0800 KVO[61945:2417667] context:(null)
2020-06-27 22:56:25.705589+0800 KVO[61945:2417667] keyPath:height
2020-06-27 22:56:25.705745+0800 KVO[61945:2417667] object:NSKVONotifying_NSPerson
2020-06-27 22:56:25.705950+0800 KVO[61945:2417667] change:{
kind = 1;
new = 182;
old = 180;
}
2020-06-27 22:56:25.706678+0800 KVO[61945:2417667] context:(null)












网友评论