[IOS开发] NSNotificationCenter消息通信机制

来源:互联网 发布:实木颗粒板 知乎 编辑:程序博客网 时间:2024/05/22 13:31

NSNotificationCenter是专门供程序中不同类间的消息通信而设置的.  这个类似于Android中的广播。我们可以收广播 (包括系统发的广播) ,发广播。

当然要点也是一样的,先注册监听某种广播,指定回调方法,不需要是还要移除广播。。下面我们来看具体用法。

1.注册通知

[[NSNotificationCenter defaultCenter]addObserver:selfselector:@selector(doSomeThing:)name:@"notification"object:nil];

  addObserver:指定观察者,即通知接受者

  selector:指定回调方法

  name:通知的名称,也就是通知的标志

  object:发送者。nil代表所有发送者

2.发送通知

[[NSNotificationCenter defaultCenter]postNotificationName:@"notification" object:dict];

postNotificationName:指定通知唯一标志。

object: NSDictionary 附加参数

3取消注册

我们在dealloc里面调用

 [[NSNotificationCenter defaultCenter] removeObserver:self name:@"notification" object:nil]; 就可以取消掉。

4.接受系统的通知

1.Application进入后台的通知

  UIApplication *app = [UIApplication sharedApplication];

    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(onApplicationEnterBack:) name:UIApplicationDidEnterBackgroundNotification object:app];

2.键盘弹起或隐藏

   //键盘升起

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];

    //键盘降下

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil]

more。。。

0 0
原创粉丝点击