KVO(Key Value Observing,即键值监听)
KVO机制NSKeyValueObserving协议提供支持,NSObject遵守了该协议,因此NSObject的子类都可使用该协议中的方法
例子
假设我们要监听UitextFild中的text值的变化
#import "ViewController.h"
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UITextField *textField;//Main.storyboard的rootVC创建的
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self.textField addObserver:self forKeyPath:@"text" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];
self.textField.text = @"123";
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
NSLog(@"%s",__func__);
NSLog(@"被修改的keyPath为%@",keyPath);
NSLog(@"被修改的对象为:%@",object);
NSLog(@"被修改的属性值为%@",[change objectForKey:@"new"]);
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
self.textField.text = @"520250";
}
- (void)dealloc {
[self.textField removeObserver:self forKeyPath:@"text"];
}
Screenshot 2018-07-27_15-11-43.png
当点击屏幕的时候打印输出
被修改的属性值为520250
注意:只有当用代码设置UitextFild的text属性时才会被监听
网友评论