iOS---NSNotification使用解析

一、使用步骤
使用NSNotification很简单, 只要三步
1、添加观察者 在需要的地方注册要观察的通知

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(update:) name:@"userName" object:nil];

2、发送通知 在某地方发送通知

NSDictionary *dict =[[NSDictionary alloc] initWithObjectsAndKeys:self.userNameTextField.text, @"userNameKey", nil];
[[NSNotificationCenter defaultCenter] postNotificationName:@"userName" object:self userInfo:dict];

3、移除观察者 移除通知

[[NSNotificationCenter defaultCenter] removeObserver:@"userName"];

二、参数解析

    1、[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(update:) name:@"userName" object:nil];
    参数说明:   
            1)观察者,self代表本控制器
            2)接收到通知后调用的方法 @selector(update:)
            3)通知名称 @"userName"
            4)接收哪个发送者的通知。 nil代表接收所有发送者的通知
    2、[[NSNotificationCenter defaultCenter] postNotificationName:@"userName" object:self userInfo:dict];
    参数说明:
            1)通知名称 @"userName"
            2)通知发送者 self
            3)附带的信息 dict(如需要传的数据)
 3、[[NSNotificationCenter defaultCenter] removeObserver:@"userName"];
    参数说明:
            1)通知名称 @"userName"

总结:由此可见都需要通知名称,而且都一样,为了避免通知名称错误,可以写成宏。

三、注意事项
1、注册了观察通知的控制器就要移动要观察的通知。这是因为,当控制器因为某些原因比如内存问题而被销毁的时候,通知中心被注册的该通知还是存在的。而当其他有地方发送该通知的时候,通知中心会继续转发,但是转发的对象已经不存在了,这时候就会crash了。所有有添加就要有移除。

2、有些可能习惯在viewWillAppear和viewWillDisappear方法中配对使用,

- (void)viewWillAppear:(BOOL)animated
 {
 [super viewWillAppear:animated];

 // 注册通知
 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(update:) name:@"userName1" object:nil];
 }

 - (void)viewWillDisappear:(BOOL)animated
 {
 [super viewWillDisappear:animated];
 [[NSNotificationCenter defaultCenter] removeObserver:@"userName1"];
 }

不是说不行,但是这两个方法属于会被经常调用的方法,比如左滑右滑的时候会重复调用,还是要多考虑一下业务逻辑,避免不要的坑,
所以建议在viewDidLoad中注册通知,在dealloc中移除通知 (注:在ARC模式下 dealloc不需要 [super dealloc])

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:@"userName"];
}

3、通知使用比较简单,适用场景 1对多模式 发出一个通知,多个对象监听。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

建古

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值