iOS观察者模式

2018-07-07  本文已影响27人  Jorunk

观察者模式(Observer Pattern):定义对象间的一种一对多依赖关系,使得每当一个对象状态发生改变时,其相关依赖对象皆得到通知并被自动更新。

当对一个对象的改变需要同时改变其它对象, 而不知道具体有多少对象有待改变;或者一个对象必须通知其它对象,而它又不能假定其它对象是谁,换言之,我们不希望这些对象是紧密耦合的。这时我们就可以利用到观察者模式。

NSNotificationCenter

NSNotificationCenter
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notice:) name:@"tongzhi" object:nil];

-(void)notice:(id)sender{  
  NSLog(@"%@",sender);
}

注意点:通知中心不会对观察者进行引用计数+1的操作,因此我们在观察者对象释放前,一定要在合适时机注销注册。否则通知中心任会向已释放的观察者发送通知,可能导致程序崩溃

//创建通知对象
NSNotification *notification = [NSNotification notificationWithName:@"123" object:nil];
 //Name是通知的名称 object是通知的发布者(是谁要发布通知,也就是对象) userInfo是一些额外的信息(通知发布者传递给通知接收者的信息内容,字典格式)
//    [NSNotification notificationWithName:@"123" object:nil userInfo:nil];
//发送通知
 [[NSNotificationCenter defaultCenter] postNotification:notification];
- (void)dealloc {
  //删除根据name和对象,如果object对象设置为nil,则删除所有叫name的,否则便删除对应的
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"tongzhi" object:nil];
}

KVO

是一种没有中心枢纽的观察者模式的实现方式。一个主题对象管理所有依赖于它的观察者对象,并且在自身状态发生改变的时候主动通知观察者对象。

[object addObserver:self forKeyPath:property options:NSKeyValueObservingOptionNew context:]。
响应观察者
observeValueForKeyPath:ofObject:change:context:

4.注销观察者

 [object removeObserver:self forKeyPath:property]。
```. 
上一篇下一篇

猜你喜欢

热点阅读