iOS NSNotificationCenter通知中心使用小结

2020-01-21 07:35:06于海丽

场景二: 

A和B是两个不相干的关系,A不知道B,B也不知道A,那么这时候如果通过delegate就没办法做到,会相对复杂。所以可以通过NSNotifcation去做一些消息传递。 

所以使用delegate的情况是两者有直接的关系,至于一方知道另一方的存在。而NSNotifcation一般是大家不知道对方的存在,一般是使用跨模块的时候使用。在使用的时候,使用delegate可能需要多写一些delegate去实现,代码量比较多。NSNotication只要定义相关的NotificationName就可以很方便的沟通。两者各有所长。

二、监听系统自带的NSNotification

系统里定义了许多的 XxxNotification 名称,其实只要 Cmd+Shift+O 打开 Open Quickly,输入 NSNotification 或者 UINotification 可以看到许多以 Notification 结尾的变量定义,由变量名称也能理解在什么时候会激发什么事件,一般都是向 [NSNotificationCenter defaultCenter] 通知的。

iOS,NSNotificationCenter,通知中心

使用步骤

第一步:注册系统监听事件


 //在NSNotificationCenter中注册键盘弹出事件
  [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardUpEvent:) name:UIKeyboardDidShowNotification object:nil];
  //在NSNotificationCenter中注册键盘隐藏事件
  [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDownEvent:) name:UIKeyboardDidHideNotification object:nil];
  //在NSNotificationCenter中注册程序从后台唤醒事件
  [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(becomeActive:) name:UIApplicationDidBecomeActiveNotification object:nil];