iOS之观察者模式(Observer Pattern)

来源:互联网 发布:彩虹秒赞源码 编辑:程序博客网 时间:2024/06/05 02:21

观察者模式


1. 用途


  • 消息触发,使得到通知的对象进行更新

2. 优点


  • 抽象耦合

3. 缺点


  • 会影响运行效率和开发效率

4. 模型


4.1 消息中心

  • 发送者发送消息给消息中心(NSNotificationCenter)
  • 消息中心收到消息后发给观察者
  • 观察者检测消息,对消息过滤,并作相应处理
  • 一对多

应用场景

  • 窗口变化
  • 系统键盘弹出隐藏
  • UITextField文本变化
  • MPMoviePlayerController

4.2 KVC/KVO (Key-Value-Coding/Observing)

  • 消息发送到NSOperationQueue
  • 遍历NSOperationQueue中的NSOperation, 进行处理和更新
  • 一对一

应用举例

♦ 定义一个Student类

@interface HJStudent : NSObject@property (nonatomic, copy) NSString *name;@property (nonatomic, assign) NSInteger age;@end

♦ 在Controller中定义一个student属性

@property (nonatomic, strong) HJStudent *student;

♦ 添加observer

self.student = [[HJStudent alloc] init];self.student.name = @"Smith"; //属性赋值,相当于调用setName()[self.student setValue:@"23" forKey:@"age"]; // kvc赋值[self.student addObserver:self forKeyPath:@"age" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil]; // 给age添加观察者

♦ 添加button改变age的值

- (IBAction)addValue:(id)sender {    self.student.age += 2;}

♦ 值改变后的回调

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {    NSLog(@"age after adding two: %@", [self.student valueForKey:@"age"]);//通过kvc取值}

点击button,每点一次age都会增加2,打印如下:

HJKVC[35692:4084259] age after adding two: 25
HJKVC[35692:4084259] age after adding two: 27
HJKVC[35692:4084259] age after adding two: 29

通过KVC/KVO, 可以在观察值改变后方便其它模块更新相应的处理。

在swift中,KVC/KVO可以通过didSet形式:

var age: Int = 12 {        didSet {            print("age has been changed to \(age)")        }    }

点击button, 打印如下:

age has been changed to 14
age has been changed to 16

0 0
原创粉丝点击