您的位置:首页 > 移动开发 > IOS开发

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.移除观察者。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: