一、通知
通知是iOS中的一种消息传递方式,通过消息中心(NSNotificationCenter)对消息的监听,当某些类发送出消息的时候,消息中心监听到这些消息,然后进行相应的操作,这些操作对于发送出这些消息的类来说是相同的。
下面通过一个demo来说明通知的实现
就是点击按钮,弹出弹窗,然后点击弹窗中的按钮打印出一些信息。 这个信息是由前面自定义的alertView发出给到控制器的,我们用通知来实现这之间的数据传递。
//viewController.m
- (IBAction)buttonDidClicked:(UIButton *)sender {
LSRAlertView * view = [LSRAlertView alertWithTitle:@"操作完成" andTitleImageName:@"gou"];
[view addTopButtonWithTitle:@"确定"];
[view addBottomButtomWithTitle:@"取消"];
[view show];
//这里向消息中心注册消息
//obsever:观察者,谁来监听这个消息
//selector:监听到发出的对应的消息后要做什么
//name:监听的消息的名称
//obeject:保存在消息中心的数据,一般传一个nil
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(sureButtonDidClicked) name:@"SureButtonClickedNotificationName" object:nil];
//取消按钮我们需要传递一些参数
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(cancelButtonClicked:) name:@"CancelButtonClickedNotificationName" object:nil];
}
首先在控制器中添加一个按钮点击事件,然后设置弹窗视图(至于如何自定义弹窗视图,请查看我的上一篇文章),接着我们在这里向消息中心注册消息,为什么在这里注册呢?因为我们是要在控制器中获取到弹窗视图的数据,在控制器中注册相应的消息后,控制器就会监听发出我们注册消息的对象,然后执行相应的方法,所以在控制器中注册消息。
接着我们在自定义弹窗视图的类写发送消息的代码,那么又该在哪里写呢?应该在弹窗视图上的按钮被点击了之后写,所以:
//LSRAlertView.m
- (IBAction)topButonClicked:(UIButton *)sender {
[self dismiss];
//这里按钮被点击了,此时需要发出消息
//name:消息的名称,必须和所监听的消息的名称相同
//object:需要回调的数据
//userInfo:也是需要回调的数据
[[NSNotificationCenter defaultCenter]postNotificationName:@"SureButtonClickedNotificationName" object:nil userInfo:nil];
}
- (IBAction)bottomButtonClicked:(UIButton *)sender {
//发出消息的时候回调参数
[self dismiss];
[[NSNotificationCenter defaultCenter]postNotificationName:@"CancelButtonClickedNotificationName" object:@"object" userInfo:@{@"name":@"jack"}];
}
发送消息我们用postNotificationName,这里需要注意的是发送消息的名称一定要和之前在控制器中注册的消息名对应起来,另外如果我们需要传递一些数据,就将传递的数据写在 object 或者 userInfo 中,前者是一个字符串类型,后者是一个字典类型。
然后是我们在控制器监听到弹窗视图发出的消息后执行的操作:
//ViewController.m
-(void)sureButtonDidClicked{
//这里不需要回调参数
NSLog(@"确定按钮被点击了");
//在这里移除消息
[[NSNotificationCenter defaultCenter]removeObserver:self name:@"SureButtonClickedNotificationName" object:nil];
}
-(void)cancelButtonClicked:(NSNotification *)notification{
//这里将传递过来的参数打印出来
NSLog(@"%@",notification.object);
NSLog(@"%@",notification.userInfo);
//同样在这里移除消息
[[NSNotificationCenter defaultCenter]removeObserver:self name:@"CancelButtonClickedNotificationName" object:nil];
}
这里需要注意两点,一是如何取出消息中的数据,我们使用notification的属性object和userInfo来取得相应的数据。第二点也是非常重要的就是一定要将消息中的消息移除,一定要将消息中的消息移除,一定要将消息中的消息移除。如果不移除就会导致点击一次按钮触发多次事件,因为有多个相同的消息同时注册了。
最后是打印的信息: