通知模式比观察者模式耦合度更低;观察者模式下被观察的对象是被动监听,而通知模式中被监听的对象是主动发出通知。
接收通知的一方需要使用如下方法添加监听:
[[NSNotificationCenter defaultCenter] addObserver:obj selector:@selector(action) name:@"notificationName"];
这里Observer后跟接收通知者;selector用来选择收到通知触发的方法,可带参数(NSNotification *)notification ;name是通知的名字,用来唯一标识通知。
发通知的一方使用的方法为:
[[NSNotificationCenter defaultCenter] postNotificationName:@"notificationName" object:obj];
这里postNotificationName是通知的名字,用来唯一标识通知;object是传递过去需要操作的对象。