通知中心
(NSNotificationCenter)
提供了相应的方法来帮助发布通知
- ( void )postNotification:( NSNotification *)notification;
➢ 发布一个 notification 通知,可在 notification 对象中设置 通知的名称 、 通知发布者 、 额外信息 等
- ( void )postNotificationName:( NSString *)aName object:( id )anObject;
➢ 发布一个名称为 aName 的通知, anObject 为这个通知的发布者
- ( void )postNotificationName:( NSString *)aName object:( id )anObject userInfo:( NSDictionary *)aUserInfo;
- ( void )postNotification:( NSNotification *)notification;
➢ 发布一个 notification 通知,可在 notification 对象中设置 通知的名称 、 通知发布者 、 额外信息 等
- ( void )postNotificationName:( NSString *)aName object:( id )anObject;
➢ 发布一个名称为 aName 的通知, anObject 为这个通知的发布者
- ( void )postNotificationName:( NSString *)aName object:( id )anObject userInfo:( NSDictionary *)aUserInfo;
➢
发布一个名称为
aName
的通知,
anObject
为这个通知的发布者,
aUserInfo
为额外信息
通知中心
(NSNotificationCenter)
提供了方法来注册一个监听通知的监听器
(Observer)
- ( void )addObserver:( id )observer selector:( SEL )aSelector name:( NSString *)aName object:( id )anObject;
➢ observer :监听器,即谁要接收这个通知
➢ aSelector :收到通知后,回调监听器的这个方法, 并且把通知对象当做参数传入
➢ aName :通知的名称。如果为 nil ,那么无论通知的名称是什么,监听器都能收到这个通知
- ( void )addObserver:( id )observer selector:( SEL )aSelector name:( NSString *)aName object:( id )anObject;
➢ observer :监听器,即谁要接收这个通知
➢ aSelector :收到通知后,回调监听器的这个方法, 并且把通知对象当做参数传入
➢ aName :通知的名称。如果为 nil ,那么无论通知的名称是什么,监听器都能收到这个通知
➢
anObject
:通知发布者。如果为
anObject
和
aName
都为
nil
,监听器都收到所有的通知
- 通知中心不会保留(retain)监听器对象,在通知中心注册过的对象,必须在该对象释放前取消注册。否则,当相应的通知再次出现时,通知中心仍然会向该监听器发送消息。因为相应的监听器对象已经被释放了,所以可能会导致应用崩溃
■ 通知中心提供了相应的方法来取消注册监听器
➢ - (void)removeObserver:(id)observer;
➢ - (void)removeObserver:(id)observer name:(NSString *)aName object:(id)anObject;
■ 一般在监听器销毁之前取消注册(如在监听器中加入下列代码):
- (void)dealloc {
//[super dealloc]; 非ARC中需要调用此句
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- 我们经常需要在键盘弹出或者隐藏的时候做一些特定的操作,因此需要监听键盘的状态
键盘状态改变的时候,系统会发出一些特定的通知
➢ UIKeyboardWillShowNotification // 键盘即将显示
➢ UIKeyboardDidShowNotification // 键盘显示完毕
➢ UIKeyboardWillHideNotification // 键盘即将隐藏
➢ UIKeyboardDidHideNotification // 键盘隐藏完毕
➢ UIKeyboardWillChangeFrameNotification // 键盘的位置尺寸即将发生改变
➢ UIKeyboardDidChangeFrameNotification // 键盘的位置尺寸改变完毕
- 系统发出键盘通知时,会附带一下跟键盘有关的额外信息(字典),字典常见的key如下:
➢ UIKeyboardFrameBeginUserInfoKey // 键盘刚开始的frame
➢ UIKeyboardFrameEndUserInfoKey // 键盘最终的frame(动画执行完毕后)
➢ UIKeyboardAnimationDurationUserInfoKey // 键盘动画的时间
➢ UIKeyboardAnimationCurveUserInfoKey // 键盘动画的执行节奏(快慢)