监听者模式之KVO的总结

一、使用方法
1、注册
NSKeyValueObservingOptionNew:change字典包括改变后的值
NSKeyValueObservingOptionOld: change字典包括改变前的值
NSKeyValueObservingOptionInitial:注册后立刻触发KVO通知
NSKeyValueObservingOptionPrior:值改变前是否也要通知(这个key决定了是否在改变前改变后通知两次)

//监听姓名属性的变化
[person addObserver:self forKeyPath:@"name" options:NSKeyValueObservingOptionNew context:nil];

2、实现回调方法

 - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:        (id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
{
  if ([keyPath isEqualToString:@"name"]) {
    
    NSLog(@"Name is changed new = %@",[change objectForKey:NSKeyValueChangeNewKey]);
    
}else
{
    [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}

}

3、移除通知
- (void)dealloc
{
[self.person removeObserver:self forKeyPath:@"name" context:nil];
}

二、经典的KVO使用场景(model与view同步)

 - (void)testKVO
 {
Person *person = [Person new];
self.person = person;
[person addObserver:self forKeyPath:@"age" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];
 }

  //实现回调
 - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
{
if ([keyPath isEqualToString:@"age"]) {
    
    NSString *old = [change objectForKey:NSKeyValueChangeOldKey];
    NSString *nw = [change objectForKey:NSKeyValueChangeNewKey];
    
   // self.oldValueLB.text = old;
    self.valueLB.text = nw;
    NSLog(@"%@ %@",old,nw);
    
}else
{
    [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];;
}
}

//移除
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
[self.person removeObserver:self forKeyPath:@"age" context:nil];
}

 - (IBAction)button:(id)sender {

self.person.age = [NSString stringWithFormat:@"%u",arc4random()%100];//取余

}

三、手动设置KVO通知

- (void)setAge:(NSString *)age
{
if ([age integerValue] < 18) {
    
    NSLog(@"未成年");
    
  }

[self willChangeValueForKey:age];

_age = age;

[self didChangeValueForKey:age];

}

//不自动
+ (BOOL)automaticallyNotifiesObserversOfAge
{
return NO;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 转载:http://yulingtianxia.com/blog/2014/05/12/objective-czh...
    F麦子阅读 987评论 0 0
  • 本文讲述了使用Cocoa框架中的KVC和KVO,实现观察者模式 键/值编码中的基本调用包括-valueForKey...
    茗涙阅读 703评论 0 3
  • 本文结构如下: Why? (为什么要用KVO) What? (KVO是什么) How? ( KVO怎么用) Mo...
    等开会阅读 1,661评论 1 21
  • 本文由我们团队的 纠结伦 童鞋撰写。 文章结构如下: Why? (为什么要用KVO) What? (KVO是什么...
    知识小集阅读 7,424评论 7 105
  • 本文转自:Objective-C中的KVC和KVO. KVC KVO2.1. Registering for Ke...
    0o冻僵的企鹅o0阅读 427评论 0 3