初识Objecive-C 之 通知
2013-10-26 09:25
281 查看
通知(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
自定义通知:
注册通知
创建并发送通知
移除监听者
#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
相关文章推荐
- 初识Objecive-C 之 NSDictionary
- 初识Objecive-C 之 内存管理
- 初识Objecive-C 之 键值编码(KVC)
- 初识iOS中的通知中心
- 初识Objecive-C 之 类目、延展、协议
- 初识Objecive-C 之 面向对象(二)
- 初识Objecive-C 之 键值观察(KVO)
- 初识Objecive-C 之 单例模式
- 初识iOS中的通知中心【图文+视频】
- 初识Objecive-C之 委托模式
- 初识Objecive-C 之 面向对象(一)
- 初识Objecive-C 之 属性
- 初识Objecive-C 之 多态不得不说的故事
- 初识Objecive-C 之 NSString
- 初学安卓路之初识Notification(通知)
- 初识Objecive-C 之 继承
- 初识Objecive-C 之 NSArray
- 初识Objecive-C 之 self关键字
- 初识PHP文件缓存
- iOS基础 - 通知中心(NSNotificationCenter)