iOS中委托模式和消息机制基本上开发中用到的比较多,一般最开始页面传值通过委托实现的比较多,类之间的传值用到的比较多,不过委托相对来说只能是一对一,比如说页面A跳转到页面B,页面的B的值改变要映射到页面A,页面C的值改变也需要映射到页面A,那么就需要需要两个委托解决问题。NSNotificaiton则是一对多注册一个通知,之后回调很容易解决以上的问题。
消息通知中重要的两个类:
(1)NSNotificationCenter: 实现NSNotificationCenter的原理是一个观察者模式,获得NSNotificationCenter的方法只有一种,那就是[NSNotificationCenter defaultCenter] ,通过调用静态方法defaultCenter就可以获取这个通知中心的对象了。NSNotificationCenter是一个单例模式,而这个通知中心的对象会一直存在于一个应用的生命周期。
(2) NSNotification: 这是消息携带的载体,通过它,可以把消息内容传递给观察者。
1.通过NSNotificationCenter注册通知NSNotification,viewDidLoad中代码如下:
- [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationFirst:) name:@"First" object:nil];
- [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationSecond:) name:@"Second" object:nil];
第一个参数是观察者为本身,第二个参数表示消息回调的方法,第三个消息通知的名字,第四个为nil表示表示接受所有发送者的消息~
回调方法:
- -(void)notificationFirst:(NSNotification *)notification{
- NSString *name=[notification name];
- NSString *object=[notification object];
- NSLog(@"名称:%@----对象:%@",name,object);
- }
- -(void)notificationSecond:(NSNotification *)notification{
- NSString *name=[notification name];
- NSString *object=[notification object];
- NSDictionary *dict=[notification userInfo];
- NSLog(@"名称:%@----对象:%@",name,object);
- NSLog(@"获取的值:%@",[dict objectForKey:@"key"]);
- }
2.消息传递给观察者:
- [[NSNotificationCenter defaultCenter] postNotificationName:@"First" object:@"博客园-Fly_Elephant"];
- NSDictionary *dict=[[NSDictionary alloc]initWithObjects:@[@"keso"] forKeys:@[@"key"]];
- [[NSNotificationCenter defaultCenter] postNotificationName:@"Second" object:@"http://www.cnblogs.com/xiaofeixiang" userInfo:dict];
3.页面跳转:
- -(void)pushController:(UIButton *)sender{
- ViewController *customController=[[ViewController alloc]init];
- [self.navigationController pushViewController:customController animated:YES];
- }
4.销毁观察者
- -(void)dealloc{
- NSLog(@"观察者销毁了");
- [[NSNotificationCenter defaultCenter] removeObserver:self];
- }
也可以通过name单个删除:
- [[NSNotificationCenter defaultCenter] removeObserver:self name:@"First" object:nil];
5.运行结果
- 2015-04-26 15:08:25.900 CustoAlterView[2169:148380] 观察者销毁了
- 2015-04-26 15:08:29.222 CustoAlterView[2169:148380] 名称:First----对象:博客园-Fly_Elephant
- 2015-04-26 15:08:29.222 CustoAlterView[2169:148380] 名称:Second----对象:http://www.cnblogs.com/xiaofeixiang
- 2015-04-26 15:08:29.223 CustoAlterView[2169:148380] 获取的值:keso