前面我们说到了代理传值,代理传值是一对一的传值方式,今天我们说一下通知,通知类似于广播,只管是谁发出的,并不管谁接收,所以是一对多的传值方式,然后我们要用的地方添加观察者监听这个通知,观察者是添加到通知中心的,通知只要一发出,我们这里接收到了就做出想做的动作,操作完毕之后记得要在通知中心将观察者移除掉。
下面来看一下具体的实现:
// 发送一个通知
// Name 标示通知(唯一的)
// object 传递的对象
[[NSNotificationCenter defaultCenter] postNotificationName:@"这是一个通知" object:nil];
// 接收通知
// 添加观察者
// 第一个参数:观察者的对象 self
// 第二个参数:接收通知后调用的方法
// 可以传递参数,而参数的对象是NSNotification的对象,可以获取通知的名字,传递的对象 用户信息
// 第三个参数:接收通知的名字
// 第四个参数: 接收谁发过来的通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(alertView:) name:@"这是一个通知" object:nil];
//观察者绑定的方法
- (void)alertView:(NSNotification *)notification{
UIAlertAction *action = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
NSLog(@"取消了");
}];
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"通知" message:notification.name preferredStyle:UIAlertControllerStyleAlert];
[alert addAction:action];
[self presentViewController:alert animated:YES completion:^{
}];
}
- (void)dealloc{
// 在此方法中移除
[[NSNotificationCenter defaultCenter] removeObserver:self];
// 移除指定名字的通知
// [[NSNotificationCenter defaultCenter] removeObserver:<#(id)#> name:<#(NSString *)#> object:<#(id)#>];
// ARC 下不需要加 retain release
// [super dealloc];
}
当我们发出通知后,观察者接收到通知,做出了弹框的操作,记得在这个页面销毁的时候将这次的通知的观察者从通知中心移除掉,不然会出现一些很奇怪的现象啊~
除了我们发送的通知以外,系统也会发送一些通知,比如内存警告啊,键盘的出现啊等等,我们可以捕获这些通知,然后做出相应操作
// 已经激活的通知
// UIApplicationDidBecomeActiveNotification
// 屏幕旋转的通知
// UIApplicationDidChangeStatusBarFrameNotification
// 键盘显示的通知
// UIKeyboardDidShowNotification
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardAppearance:) name:UIKeyboardDidShowNotification object:nil];
- (void)keyboardAppearance:(NSNotification *)notification{
NSLog(@"键盘的信息 %@",notification.userInfo);
}
然后我们就能拿到键盘的信息了