iOS NSNotificationCenter简介

NSNotificationCenter通知是一种消息广播的实现机制,可以在不同对象之间发送通知进而实现通信。

1. 通知中心

整个系统只有一个通知中心

NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];

常用方法

/**
 * 添加通知监听器
 * observer为监听器
 * aSelector为接到收通知后的处理函数
 * aName为监听的通知的名称
 * anObject为接收通知的对象,需要与postNotification的object匹配
 */
- (void)addObserver:(id)observer selector:(SEL)aSelector name:(nullable NSNotificationName)aName
            object:(nullable id)anObject;

/**
 * 发送通知
 * notification为NSNotification对象
 */
- (void)postNotification:(NSNotification *)notification;

/**
 * aName为监听的通知的名称
 * anObject为接收通知的对象
 * aUserInfo为字典类型的数据,可以传递相关数据
 */
- (void)postNotificationName:(NSNotificationName)aName object:(nullable id)anObject;
- (void)postNotificationName:(NSNotificationName)aName object:(nullable id)anObject
            userInfo:(nullable NSDictionary *)aUserInfo;

/**
 * 删除监听器
 */
- (void)removeObserver:(id)observer;

/**
 * 删除通知的监听器
 * aName监听的通知的名称
 * anObject监听的通知的发送对象
 */
- (void)removeObserver:(id)observer name:(nullable NSNotificationName)aName
            object:(nullable id)anObject;

添加监听器时,如果指定了anObject对象,只能接收anObject为同一对象的通知。
发出通知时,如果指定了anObject对象,没有指定anObject对象的监听器同样可以收到。

2. Notification通知

NSNotification包含了一些用于向其他对象发送通知的必要信息,NSNotification是一个不可变的对象。

// 通知的唯一标识,用于辨别通知对象
@property(readonly, copy) NSNotificationName name;
// 定义一个对象
@property(nullable, readonly, retain) id object;
// 字典对象,可以用其来进行传值
@property(nullable, readonly, copy) NSDictionary *userInfo;

- (instancetype)initWithName:(NSNotificationName)name object:(nullable id)object
            userInfo:(nullable NSDictionary *)userInfo
+ (instancetype)notificationWithName:(NSNotificationName)aName object:(nullable id)anObject;
+ (instancetype)notificationWithName:(NSNotificationName)aName object:(nullable id)anObject
            userInfo:(nullable NSDictionary *)aUserInfo;

3. 一般用法

viewDidLoad里添加通知监听器,在dealloc中删除通知监听器。

- (void)viewDidLoad {
    [super viewDidLoad];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:)
                 name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:)
                 name:UIKeyboardWillHideNotification object:nil];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)keyboardWillShow:(NSNotification *)notification {
}

- (void)keyboardWillHide:(NSNotification *)notification {
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值