单休的日子很有意思,很想用周日的时间好好睡觉,但是呢,还是想抽出来点时间回忆一下之前学过的知识,今天把通知逆向传值方法复习一下,慢慢复习,慢慢写,把之前学过的知识都写在博客里,希望自己能够深刻记住这些知识点,也希望能够给同行们在工作和学习上带来帮助;
少说废话,上代码:
首先有两个控制器:
ViewController(我比较懒,没有自己创建控制器);
SecondViewController(要跳转到的第二个控制器);
实现功能:在 SecondViewController 消失之前传一个对象(测试传的是字符串)给 ViewController,并显示在label上面;
#import "ViewController.h"
#import "SecondViewController.h"
@interface ViewController ()
@property (nonatomic,weak) UILabel *label;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//创建一个进入下一个控制器的按钮
UIButton *nextBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 100, 100, 100)];
[nextBtn addTarget:self action:@selector(nextBtnClick:) forControlEvents:UIControlEventTouchDown];
[nextBtn setTitle:@"nextVC" forState:UIControlStateNormal];
nextBtn.backgroundColor = [UIColor cyanColor];
[self.view addSubview:nextBtn];
//创建一个label,用来现实下一个控制器传过来的值
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 300, self.view.bounds.size.width, 50)];
label.backgroundColor = [UIColor redColor];
[self.view addSubview:label];
self.label = label;
//创建通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getValueFromSecondVC:) name:@"ViewControllerNotificationCenter" object:nil];
}
/**
* 点击按钮跳转控制器
*
* @param nextBtn nextBtn
*/
- (void)nextBtnClick:(UIButton *)nextBtn
{
//创建第二个控制器
SecondViewController *secondVC = [[SecondViewController alloc] init];
//跳转
[self presentViewController:secondVC animated:YES completion: nil];
}
/**
* 监听收到通知的方法
*
* @param notification notification
*/
- (void)getValueFromSecondVC:(NSNotification *)notification
{
//现实收到的信息
self.label.text = notification.object;
}
@end
SecondViewController.m
#import "SecondViewController.h"
@interface SecondViewController ()
@end
@implementation SecondViewController
- (void)viewDidLoad {
[super viewDidLoad];
//设置背景颜色
self.view.backgroundColor = [UIColor whiteColor];
//创建一个返回按钮
UIButton *backBtn = [[UIButton alloc] initWithFrame:CGRectMake(100, 100, 100, 100)];
backBtn.backgroundColor = [UIColor magentaColor];
[backBtn setTitle:@"back" forState:UIControlStateNormal];
[backBtn addTarget:self action:@selector(backBtnClick:) forControlEvents:UIControlEventTouchDown];
[self.view addSubview:backBtn];
}
/**
* 返回按钮事件
*
* @param backBtn backBtn
*/
- (void)backBtnClick:(UIButton *)backBtn
{
//发送通知,我要传值了,传送的值可以是任何oc对象,这里是一个字符串@"secondVCObject";
[[NSNotificationCenter defaultCenter] postNotificationName:@"ViewControllerNotificationCenter" object:@"secondVCObject"];
//隐藏本控制器
[self dismissViewControllerAnimated:YES completion:nil];
}
@end
没有点击nextVC按钮之前界面:
点击按钮之后,跳转到第二个控制器界面:
点击返回按钮之后:
总结:是不是很好玩,通知传值很方便,很容易理解,但是呢,代码量相对于代理方法多很多,所以,在实现简单的传值的时候,使用通知还是蛮好的;
如果转载请注明转于:AirZilong的博客