Model.h文件
#import <Foundation/Foundation.h>
@interface Model : NSObject
@property (nonatomic, copy)NSString * name;
@end
ViewController.m文件
#import "ViewController.h"
#import "Model.h"
@interface ViewController ()
//声明一个Model属性
@property (nonatomic, strong)Model * model;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//实例化Model并给其属性赋值
self.model = [[Model alloc] init];
self.model.name = @"000";
//给model的name属性添加观察者
//_model:被监听的对象 @“name” :被监听的对象的属性
//self : 要进行监听的对象,可为任意对象,但此对象必须实现监听方法
//options :监听该属性的新值和旧值
//context :传递的信息
[_model addObserver:self forKeyPath:@"name" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:@"我的值变了"];
}
//触摸屏幕改变model的name属性的值
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
self.model.name = @"123";
}
//当监听的属性值发生变化时就会出发这个方法
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
if ([keyPath isEqualToString:@"name"]) {
NSLog(@"%@", [object class]); //被监听的对象
NSLog(@"%@",change); //字典存储监听的值(新值,旧值)
NSLog(@"%@", context); //传递过来的信息
}
}