iOS—NSNotificationCenter
2014-12-26 14:40
369 查看
iOS 提供了一种 "同步的" 消息通知机制,观察者只要向消息中心注册, 即可接受其他对象发送来的消息,消息发送者和消息接受者两者可以互相一无所知,完全解耦。
这种消息通知机制可以应用于任意时间和任何对象,观察者可以有多个,所以消息具有广播的性质,只是需要注意的是,观察者向消息中心注册以后,在不需要接受消息时需要向消息中心注销,这种消息广播机制是典型的“Observer”模式。
注册通知:即要在什么地方接受消息
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(mytest:)
name:@"mytest"
object:nil];
参数介绍:
addObserver: 观察者,即在什么地方接收通知;
selector: 收到通知后调用何种方法;
name: 通知的名字,也是通知的唯一标示,编译器就通过这个找到通知的。
发送通知:调用观察者处的方法。
[[NSNotificationCenter defaultCenter]
postNotificationName:@"mytest"
object:searchFriendArray];
参数:
postNotificationName:通知的名字,也是通知的唯一标示,编译器就通过这个找到通知的。
object:传递的参数
注册方法的写法:
- (void) mytest:(NSNotification*) notification
{
id obj = [notification object];//获取到传递的对象
}
注销观察者有2个方法:
a. 最优的方法,在UIViewController.m中:
-(void)dealloc
{
[[NSNotificationCenterdefaultCenter] removeObserver:self];
}
If you see the methodyou don't need to call [super dealloc]; here, only the method without superdealloc needed.
b. 单个移除:
[[NSNotificationCenterdefaultCenter] removeObserver:self name:@"Notification_GetUserProfileSuccess"object:nil];
//例子 -----根据键盘变化,获取iPhone的不同键盘高度
1.在项目中添加监听键盘呼出事件的消息:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
2.针对键盘高度做出自适应:
- (void)keyboardWillShow:(NSNotification *)notification
{
NSDictionary *info = [notification userInfo];
//kbsize.width为键盘宽度,kbsize.height为键盘高度
CGSize kbSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
//自适应代码 ,即需要移动视图的高度代码
。。。。。。
}
3.移除观察者。
相关文章推荐
- ios NSNotificationCenter
- iOS NSNotificationCenter消息注册与撤销【转】
- iOS Delegate NSNotificationCenter
- IOS NSNotificationCenter 的使用
- IOS NSNotification Center 通知中心的使用
- IOS NSNotificationCenter
- iOS中NSNotificationCenter的简单使用
- IOS 消息机制(NSNotificationCenter)
- iOS Delegate NSNotificationCenter
- iOS NSNotificationCenter的简单使用
- iOS 通知中心 NSNotificationCenter & NSNotification
- iOS 通知中心 NSNotificationCenter & NSNotification
- ios NSNotificationCenter消息注册与撤销
- iOS NSNotificationCenter详解
- ios 通知中心 NSNotificationCenter & NSNotification
- 洪小瑶学iOS-NSNotificationCenter 详解
- iOS Delegate NSNotificationCenter
- IOS NSNotificationCenter 通知中心
- iOS NSNotificationCenter(消息机制)
- ios 在ios9中 NSNotificationCenter addObserver 不会影响对象释放