NSNotificationCenter通知基本用法(一)
2016-06-28 21:36
316 查看
ViewController.m文件中
SecondVC.m中
- (void)viewDidLoad { [super viewDidLoad]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveChangeColorNotification:) name:@"changeColorNotification" object:nil]; } - (void)receiveChangeColorNotification:(NSNotification *)noti{ //通知调用方法时传得参数是NSNotification, self.view.backgroundColor = [noti.userInfo objectForKey:@"color"]; } - (IBAction)gotoSecondVC:(UIButton *)sender { SecondVC *vc = [[SecondVC alloc] init]; [self.navigationController pushViewController:vc animated:YES]; [vc release]; }
SecondVC.m中
- (void)viewDidLoad { [super viewDidLoad]; //通知和代理相同之处:都可以实现方法调用和传值。 //不同之处:通知可以多对多传值和调用,而代理只能一对一。 通知只能实现单向传值,而代理可以实现值的回传。 NSNotificationCenter *center = [NSNotificationCenter defaultCenter]; //addObserver添加观察者(监听通知) //第一个参数是添加的观察者(让谁监听) //第二个参数是收到通知后调用的方法 //第三个参数是要监听的通知的名字(写nil的话监听所有通知) //第四个参数是限定通知来源(写nil的话不限定通知来源) [center addObserver:self selector:@selector(receiveChangeColorNotification:) name:@"changeColorNotification" object:nil]; } - (void)receiveChangeColorNotification:(NSNotification *)noti{ //通知调用方法时传得参数是NSNotification, if (noti.object != self) { self.view.backgroundColor = [noti.userInfo objectForKey:@"color"]; } } - (IBAction)colorButtonClick:(UIButton *)sender { UIColor *color = sender.tag == 1?[UIColor redColor]:sender.tag == 2?[UIColor greenColor]:[UIColor blueColor]; //通知中心,也是单例类。发通知必须通过通知中心 NSNotificationCenter *center = [NSNotificationCenter defaultCenter]; //postNotificationName发送一个通知。 //第一个参数name表示通知的名字。 //第二个参数object表示通知的发送者。 //第三个参数userInfo是通知的参数,是一个字典。 [center postNotificationName:@"changeColorNotification" object:self userInfo:@{@"color":color}]; }
- (void)dealloc{ //removeObserver取消某个对象的通知监听。 //*一个对象在被释放前一定要取消通知的监听,否则系统在发这个对象所监听的通知时,系统就会崩溃。 [[NSNotificationCenter defaultCenter] removeObserver:self]; [super dealloc]; }
相关文章推荐
- 以程序的方式操纵NTFS的文件权限
- 94. Binary Tree Inorder Traversal
- Android之adb shell dumpsys activity获取task里面的所有actitiy
- pl/sql 块和结构
- 【Android】解决在RelativeLayout中使用ImageView, adjustViewBounds 无效
- poj3468(A simple Problem with Integers)(线段树成段增减)
- sed的工作原理及使用
- action
- 对象创建,对象方法
- 基础-encodeURI
- 团体程序设计天梯赛L2-003 月饼(贪心)
- linux网络编程(一)
- c语言之split实现
- android 吐丝、指示框
- Windows平台内核级文件访问
- phpcms 一些bug
- JavaSE 基础 第04节 Java的基本元素
- Infragistics.NetAdvantage.Ultimate.2011.vol1是最后一个支持Ultrawebgrid的版本
- 问题:html中的select的options的用法?
- 动能定理