通知,就是说A观察B的情况.如果B有所改动,就通知A让A知道.这是一种松耦合的通信方式.
有两种方法:
1. NSNotificationCenter通知中心
例子如下:
//构建自定义通知事件和发送
//通知的事件名称, 和 参数
NSNotification *notification = [NSNotification notificationWithName:@"data changes" object:self];
NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
[notificationCenter postNotification:notification];
//订阅这个通知后.上边发送的消息,这里才能收到
NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
//update是收到通知后执行的方法, subject是上边传送过来的参数
[notificationCenter addObserver:self selector:@selector(update:) name:@"data changes" object:subject];
2. NSKeyValueObserving 键值对的方式
手动调用通知
在观察者的类里加上如下代码
//把自身作为观察者加到scribble里
//注册@"mark" 为键 scribble为值
[scribble addObserver:self forKeyPath:@"mark"
opations:NSKeyValueObservingOptionInitial |
NSKeyValueObservingOptionNew
context:nil];
收到通知后执行的方法
//在观察者的代码里加上处理收到通知后的方法
- (void) observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary *)change
context:(void *)context
{
//如果是来自注册mark的通知就执行并且判断发送通知的来源是否是Scribble类
if( [object is KindOfClass:[Scribble class]] && [keyPath isEqualoString:@"mark"] )
{
//NSKeyValueChangeNewKey是用来获取Scribble里改动的值
id mark = [change objectForKey:NSKeyValueChangeNewKey];
//..一些处理
}
}
在被观察者的类里加上
//在scribble类里有变动的地方执行以通知观察者
//这里执行完didChangeValueForKey后会发送一条通知执行以下代码
[self willChangeValueForKey:@"mark"];
....//一些改动
[self didChangeValueForKey:@"mark"];
至此,通知差不多就是这,慢慢练练就是熟悉了!