简单写了一个通知的demo,通过以下代码可以简单了解一下
我新建了3个UIViewController,分别命名为FirstViewController , SecondViewController , ThirdViewController
并在AppDelegate里设FirstViewController为根视图
FirstViewController
//FirstViewController.m
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.view.backgroundColor = [UIColor whiteColor];
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.backgroundColor = [UIColor yellowColor];
button.frame = CGRectMake(100, 100, 100, 100);
[button addTarget:self action:@selector(action:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
//注册通知
//参数1:添加当前对象为注册对象
//参数2:设置收到消息后触发的方法
//参数3:设置消息通知的标示符名字
//参数4:设置接收对象的参数值,设置为nil
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(changeColor:) name:@"changeColor" object:nil];
}
//通知的的触发方法
- (void)changeColor:(NSNotification *)notification{
//获得发送的消息传递过来的值
UIColor *color = [notification object];
self.view.backgroundColor = color;
}
//按钮点击触发方法,跳到SecondViewController
- (void)action:(UIButton *)btn{
SecondViewController *secondVC = [[SecondViewController alloc] init];
[self.navigationController pushViewController:secondVC animated:YES];
}
SecondViewController
//SecondViewController.m
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.view.backgroundColor = [UIColor whiteColor];
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.backgroundColor = [UIColor yellowColor];
button.frame = CGRectMake(100, 100, 100, 100);
[button addTarget:self action:@selector(action:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(changeColor:) name:@"changeColor" object:nil];
}
- (void)changeColor:(NSNotification *)notification{
//获得发送的消息传递过来的值
UIColor *color = [notification object];
self.view.backgroundColor = color;
}
- (void)action:(UIButton *)btn{
ThirdViewController *thirdVC = [[ThirdViewController alloc] init];
[self.navigationController pushViewController:thirdVC animated:YES];
}
ThirdViewController
//ThirdViewController.m
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.view.backgroundColor = [UIColor whiteColor];
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.backgroundColor = [UIColor yellowColor];
button.frame = CGRectMake(100, 100, 100, 100);
[button addTarget:self action:@selector(action:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
}
- (void)action:(UIButton *)btn{
//发送一个消息通知
//参数2:发送消息时传递的值
[[NSNotificationCenter defaultCenter]postNotificationName:@"changeColor" object:[UIColor brownColor]];
}
当点击ThirdViewController的按钮后,再返回前两页就可以发现,前两页的背景颜色变成了通知所发送的颜色了.