iOS开发————通信方式之NSNotification

NSNotification即通知,可以实现一个对象发送通知,多个对象接收到通知。


工作流程:

在需要发送通知的类中添加一个通知中心(单例)。

在需要发送通知的类中发送通知,发送通知的对象是self,可定义相应的用户信息,通知名可以是任意定义的字符串,监听通知需要和此通知名匹配。

在需要接收通知的类中添加通知的接收对象,用来监听发出的通知,下面自定义一个接收者的相应方法,方法名封装到上面的接收对象。

最后移除当前对象监听的通知。


举例:在孩子这个类中发送通知,告知孩子脏了,在保姆这个类中接收通知,并实现给孩子洗澡这个方法。


#import "Child.h"

@implementation Child

- (instancetype)init {
    
    if (self = [super init]) {
        
        _cleanValue = 100;
        _happyValue = 100;
    }
    
    [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerAction:) userInfo:nil repeats:YES];
    
    return self;
}

- (void)timerAction:(NSTimer *)timer {
    
    _cleanValue--;
    _happyValue--;
    
    NSLog(@"cleanValue:%li, happyValue:%li", _cleanValue, _happyValue);
    
    if (_cleanValue == 95) {
        
        //获取到通知中心对象----单例,在内存中只有一个通知中心对象
        NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
        
        
        //发送通知,带用户信息的通知
        //用户信息可由可无,后面被打印出来了
        NSDictionary *userInfo = @{
                                   @"name" : @"tengteng",
                                   @"age" : @"22"
                                   };
        [center postNotificationName:@"BathNotification" object:self userInfo:userInfo];
        
    }
    
}
@end

#import "Nanny.h"
#import "Child.h"
@implementation Nanny

//接受到通知后针对此事件要作出响应
- (instancetype)init {
    
    if (self = [super init]) {
        
        //监听通知
        NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
        
        [center addObserver:self selector:@selector(cleanValueAction:) name:@"BathNotification" object:nil];
    }
    
    return self;
}

- (void)cleanValueAction:(NSNotification *)notification {
    
    //保姆对小孩脏了这个事件的响应
    NSLog(@"保姆给小孩洗澡");
    
    //获取到通知的发送者,即小孩,这样才能更改小孩的洁净程度的属性
    Child *child = (Child *)notification.object;
    
    //可以通过notification来获取到通知发送者传递的信息
    NSLog(@"userInfo:%@", notification.userInfo);
    
    child.cleanValue = 100;
}

- (void)dealloc {
    
    //移除当前对象对所有通知的监听
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值