通知(Notification)是一种发给一个或者多个观察者,用来通知其他在程序中发生了某个事件的消息,Cocoa中得通知机制遵循的一种广播的模式。通知机制的核心就是一个进程中单一实例的对象,被叫做通知中心(NSNotificationCenter)。当一个对象发布一个通知时,通知会先被发布到通知中心。
自定义通知:
- 注册通知
- 创建并发送通知
- 移除监听者
#import "King.h"
@interface King ()
- (void)sameMassage;
@end
@implementation King
-(void)sameMassage{
//创建自定义通知
NSNotification *notification = [NSNotificationnotificationWithName:@"明天放假" object:self userInfo:nil];
//发送通知
[[NSNotificationCenterdefaultCenter] postNotification:notification];
}
@end
--------------------------------------
#import "Worker.h"
@interface Worker ()
-(void) say:(id) sender;
@end
@implementation Worker
- (id)init
{
self = [superinit];
if (self) {
//注册通知,对象接受通知
[[NSNotificationCenterdefaultCenter] addObserver:selfselector:@selector(say:)name:@"明天放假" object:nil];
}
return self;
}
-(void) say:(id) sender{
NSLog(@"oYear、");
}
- (void)dealloc
{
//移除监听者
[[NSNotificationCenterdefaultCenter] removeObserver:selfname:@"明天放假" object:nil];
[super dealloc];
}
@end