KVO
通过kvc的方式修改被观察者的属性时 主动通知观察者
注册observing对象addObserver:forKeyPath:options:context:委托代理
观察者类必须重写方法 observeValueForKeyPath:ofObject:change:context:
kvo是同步的
应用场景:
MVC模型中,数据库(dataModal)发生变化时,引起view改变,用这种方式实现非常方便
代码:
新建model person
@interface Person : NSObject @property (nonatomic, assign) int age; +(instancetype)personWithDict:(NSDictionary *)dict; @end +(instancetype)personWithDict:(NSDictionary *)dict { id obj = [[self alloc]init]; [obj setValuesForKeysWithDictionary:dict]; return obj; }
- (void)viewDidLoad { [super viewDidLoad]; self.person = [Person personWithDict:@{@"age":@(100)}]; /* 1.谁进行观察 2.观察哪个属性 3.观察者的选项 4.场景 可以根据监听时来判断 */ [self.person addObserver:self forKeyPath:@"age" options:NSKeyValueObservingOptionNew context:nil]; }
//添加监听后 一旦监听到更改会调用此方法 -(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context { NSLog(@"keypath:%@ obj:%@ change:%@ context:%@",keyPath,object,change,context); } -(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { self.person.age = self.person.age -1; NSLog(@"%d",self.person.age); }