NSNotificationCenter通知基本用法(一)
来源:互联网 发布:那些直播软件有黄播 编辑:程序博客网 时间:2024/06/05 22:43
ViewController.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];}
8 0
- NSNotificationCenter通知基本用法(一)
- 通知基本用法NSNotificationCenter
- NSNotificationCenter通知基本用法(二)
- NSNotificationCenter(通知中心)
- 通知中心(NSNotificationCenter)
- Android之Notification(一):通知的基本用法
- NSNotificationCenter(通知)的使用方法
- NSNotificationCenter 通知
- 通知NSNotificationCenter
- 通知--NSNotificationCenter
- 通知NSNotificationCenter
- NSNotificationCenter通知
- Objective-C NSNotificationCenter (通知)的使用方法
- iOS--通知的使用(NSNotificationCenter )
- OC——通知(NSNotificationCenter)基本声明方法
- Android 通知栏Notification总结一:基本用法
- NSNotificationCenter(通知中心)(例UIDevice通知)
- NSNotificationCenter 用法
- 团体程序设计天梯赛L2-003 月饼(贪心)
- android 吐丝、指示框
- c语言之split实现
- 中文分词算法研究
- 基础-encodeURI
- NSNotificationCenter通知基本用法(一)
- 对象创建,对象方法
- action
- poj3468(A simple Problem with Integers)(线段树成段增减)
- pl/sql 块和结构
- 94. Binary Tree Inorder Traversal
- 【Android】解决在RelativeLayout中使用ImageView, adjustViewBounds 无效
- 团体程序设计天梯赛L2-004 这是二叉搜索树吗?(数据结构)
- Light OJ 1007 Mathematically Hard [欧拉函数+前缀和]【数论】