观察者模式
观察者模式的具体应用有两个:通知(notification)和KVO(Key-ValueObserveing)机制。
1. 通知机制
- 投送对象
例:
//NSNotificationCenter是单例模式,defaultCenter是创建和共享实例的方法。三个参数分别是name/object/userInfo
[[NSNotificationCenter defaultCenter]
postNotificationName:@"RegisterCompletionNotification"
object:nil
userInfo:dataDict];
- 接受对象
注意最后一定要remove掉通知
例:
监听通知--@"RegisterCompletionNotification"
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(registerCompletion:)
name:@"RegisterCompletionNotification"
object:nil];
remove掉通知:
例
-(void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}