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 {
}