iOS—NSNotificationCenter

来源:互联网 发布:压缩文件夹 linux 编辑:程序博客网 时间:2024/06/07 05:19


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.移除观察者。




0 0
原创粉丝点击