Object-C 通知

通知

通过学习’KVO’,我们发现’KVO’是一种简单的观察者设计模式 ,涉及到两个对象,分别是观察者和被观察者。。这种 方式实质有很大局限性,那么OC的’Foundation’框架又为开发者提供了新的一种观察者设计模式,即’通知’。
通知,是一种发送给一个或者多个观察者,用来通知其在程序中发生了某个事件的消息。Cooa中的通知机制遵循的是一种广播的模式。它是一种程序中事件的发起者或者是处理着和其他想要知道该事情的对象沟通的一种方式。消息的接受者,也就是观察者响应该事件来改变自己的UI、行为或者状态。

在OC中,使用’NSNotification’类来表示一个通知。

//初始化一个NSNotification类的实例对象
    NSNotification *notification1 = [NSNotification notificationWithName:@"通知名称" object:self];

    NSNotification *notification2 = [NSNotification notificationWithName:@"通知名称" object:self userInfo:@{@"content":@"jay is on living"}];
其中:
1.name:表示通知名称,最好英文名,用来识别通知对象
2.object:表示通知的发起人
3.useInfo:表示通知的内容

在现实生活中,我们的邮件都需要由邮局发送给接收人。在OC中也一样,’Foundation’框架定义了一个单例类,通知中心,’NSNotificationCenter’来统一发送通知的实例对象给观察者

//通知中心  单例类,拿到通知中心的单例
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
//通知中心发送通知
    [center postNotification:notification1];
//简便写法,通知仲尼直接发送消息
//    [center postNotificationName:<#(NSString *)#> object:<#(id)#>]
//    [center postNotificationName:<#(NSString *)#> object:<#(id)#> userInfo:<#(NSDictionary *)#>]

建立通知发送机制,步骤如下:

1.注册相关监听者,并实现监听收到通知时的方法
2.在需要的时候,被监听的对象去通知中心发送通知。
3.在’dealloc’方法中,移除通知

-(id)init{
    if (self = [super init]) {
       //到通知中心去让自己成为某个通知的监听对象
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationAction:) name:TeacherWithStudentNotification object:nil];
    }
    return self;
}
-(void)notificationAction:(NSNotification *)notification{
    NSLog(@"notification userinfo = %@",notification.userInfo);
    NSLog(@"上厕所");

}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:TeacherWithStudentNotification object:nil];
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值