总结iOS 页面间五种传值(属性,代理 , block,单例,通知)

废话不多说下面我们就简单介绍下页面间常用的几种传值方式,希望能给初学者带来帮助:

注: 文中 ,第一个界面为FirstViewController,第二个界面为SecondViewController

(-)属性传值

属性传值(场景)一般用于正向传值,即第一个界面传值给第二个界面

属性传值是这几大传值中最简单的传值方式只需要要记住两点:
1.要在接收值的界面(SecondViewController)中声明属性即文中: labelString
2.要在跳转界面的同时将要传的赋值给下个控制器对象的属性即文中的这个操作: secondVc.labelString =textF.text;

简单的传值代码如下:
FirstViewController
#import "FirstViewController.h"
#import "SecondViewController.h"
@interface FirstViewController ()
{
    UITextField * textF;
}
@end

@implementation FirstViewController

- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor =[UIColor whiteColor];
[self creatUI];
}

-(void)creatUI{
//创建输入框
textF = [[UITextField alloc]init];
textF.frame = CGRectMake(0, 100, self.view.frame.size.width, 30);
textF.borderStyle = UITextBorderStyleRoundedRect;
[self.view addSubview:textF];
//创建跳转下个界面的按钮
UIButton * PushBtn = [UIButton buttonWithType:(UIButtonTypeSystem)];
PushBtn.frame = CGRectMake(0, 140, self.view.frame.size.width, 30);
[PushBtn setTitle:@"Push" forState:(UIControlStateNormal)];
[PushBtn addTarget:self action:@selector(PushClick:) forControlEvents:(UIControlEventTouchUpInside)];
[self.view addSubview:PushBtn];

}

//按钮点击事件
-(void)PushClick:(UIButton*)sender{

SecondViewController * secondVc = [[SecondViewController alloc]init];
 //赋值给下个控制器的属性
secondVc.labelString =textF.text;
[self.navigationController pushViewController:secondVc animated:YES];

}
SecondViewController
#import <UIKit/UIKit.h>

@interface SecondViewController : UIViewController
//声明属性:用来接收上个界面传过来的值
@property (nonatomic,copy) NSString *labelString;
@end


#import "SecondViewController.h"

@implementation SecondViewController

- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
UILabel *label = [[UILabel alloc]init];
label.frame =CGRectMake(0, 100, self.view.frame.size.width, 30);
//在标签上展示上个界面传过来的值
label.text  = _labelString;
[self.view addSubview:label];
}

(二)Block传值

block传值(场景)一般用于逆向传值,即第二个界面传值给第一个界面

block的用法很多对于初学者来说是个难点,对于传值来说看了本文你可能会觉的并没有那么难,对比属性传值,我们也需要记住两点:
1.要在第二个界面(SecondViewController.h)定义一个Block:
#import <UIKit/UIKit.h>
typedef void (^PushBlock)(NSString*);
@interface SecondViewController : UIViewController
@property (nonatomic,strong)PushBlock pushValueString;
@endpushValueString;
2.要在第一个界面(FirstViewController.m)跳转第二个界面的方法中我们为block属性赋值完成block传值:

-(void)PushClick:(UIButton*)sender{

SecondViewController * secondVc = [[SecondViewController alloc]init
secondVc.pushValueString = ^(NSString *str){
    textF.text =str;
} ;

[self.navigationController pushViewController:secondVc animated:YES];

}
Block传值完整代码如下:
FirstViewController
#import "FirstViewController.h"
#import "SecondViewController.h"
@interface FirstViewController ()
{
UITextField * textF;
}
@end

@implementation FirstViewController

- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor =[UIColor whiteColor];
[self creatUI];
}

-(void)creatUI{
textF = [[UITextField alloc]init];
textF.frame = CGRectMake(0, 100, self.view.frame.size.width, 30);
textF.borderStyle = UITextBorderStyleRoundedRect;
[self.view addSubview:textF];

UIButton * PushBtn = [UIButton buttonWithType:(UIButtonTypeSystem)];
PushBtn.frame = CGRectMake(0, 140, self.view.frame.size.width, 30);
[PushBtn setTitle:@"Push" forState:(UIControlStateNormal)];
[PushBtn addTarget:self action:@selector(PushClick:) forControlEvents:(UIControlEventTouchUpInside)];
[self.view addSubview:PushBtn];

}
//跳转下个界面点击事件
-(void)PushClick:(UIButton*)sender{

SecondViewController * secondVc = [[SecondViewController alloc]init];
//核心代码为block属性赋值
secondVc.pushValueString = ^(NSString *str){
    textF.text =str;
} ;

[self.navigationController pushViewController:secondVc animated:YES];

}
SecondViewController
#import <UIKit/UIKit.h>
typedef void (^PushBlock)(NSString*);
@interface SecondViewController : UIViewController
@property (nonatomic,strong)PushBlock pushValueString;
@end


#import "SecondViewController.h"

@interface SecondViewController ()
{

UITextField * textF;
NSString * textFString;
}
@end

@implementation SecondViewController

- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
textF = [[UITextField alloc]init];
textF.frame = CGRectMake(0, 100, self.view.frame.size.width, 30);
textF.borderStyle = UITextBorderStyleRoundedRect;
[self.view addSubview:textF];

UIButton * Backbtn = [UIButton buttonWithType:(UIButtonTypeSystem)];

Backbtn.frame  =CGRectMake(0, 140, self.view.frame.size.width, 30);

[Backbtn addTarget:self action:@selector(backClick:) forControlEvents:(UIControlEventTouchUpInside)];
[Backbtn setTitle:@"back" forState:(UIControlStateNormal)];
[self.view addSubview:Backbtn];
}
//返回第一个界面并将值带入
-(void)backClick:(UIButton*)sender{
//核心代码
_pushValueString(textF.text);
[self.navigationController popViewControllerAnimated:YES];
}

(三)代理传值

代理传值(场景)一般用于逆向传值,即第二个界面传值给第一个界面

FirstViewController页面push到SecondViewController页面,如果SecondViewController页面的信息想回传(回调)到FirstViewController页面,用代理传值,其中SecondViewController定义协议和声明代理,FirstViewController确认并实现代理,FirstViewController作为SecondViewController的代理
对于代理传值我们要记住如下记步操作:
第一步:首先,在SecondViewController.h中
(1).定义协议
(2).设置协议中的方法
(3).声明代理
然后,在SecondViewController.m中
(1).为其绑定相应方法
第二步:在FirstViewController.m中
(1).设置代理
(2).服从协议

完整代理传值代码如下:
SecondViewController
//首先在SecondViewController.h中创建协议方法
#import <UIKit/UIKit.h>
@class SecondViewController;
//定义协议
@protocol PushValueDelegate<NSObject>
@optional
//设置协议中的方法
-(void)viewController:(SecondViewController*)ViewController didPushVlaueWithInfo:(id)info;
@end
@interface SecondViewController : UIViewController
//声明代理
@property (nonatomic,assign)id<PushValueDelegate>delegate;
@end


//然后,在SecondViewController.m中我们判定代理对象存在时,为其绑定相应方法
#import "SecondViewController.h"
@interface SecondViewController ()
{
UITextField * textF;
NSString * textFString;
}
@end
@implementation SecondViewController
-(void)viewWillDisappear:(BOOL)animated{
//设置视图将要消失时.通过代理传值
//判断代理是否存在,并且设置代理能够响应代理方法时,才执行代理方法
if (self.delegate && [self.delegate respondsToSelector:@selector(viewController:didPushVlaueWithInfo:)]) {
    [self.delegate viewController:self didPushVlaueWithInfo:textF.text];
}
}

- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor redColor];
textF = [[UITextField alloc]init];
textF.frame = CGRectMake(0, 100, self.view.frame.size.width, 30);
textF.borderStyle = UITextBorderStyleRoundedRect;
[self.view addSubview:textF];

}
FirstViewController
#import "FirstViewController.h"
#import "SecondViewController.h"
//服从协议
@interface FirstViewController ()<PushValueDelegate>
{
  UITextField * textF;
}
@end

@implementation FirstViewController

- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor =[UIColor whiteColor];
[self creatUI];
  }

-(void)creatUI{
textF = [[UITextField alloc]init];
textF.frame = CGRectMake(0, 100, self.view.frame.size.width, 30);
textF.borderStyle = UITextBorderStyleRoundedRect;
[self.view addSubview:textF];

UIButton * PushBtn = [UIButton buttonWithType:(UIButtonTypeSystem)];
PushBtn.frame = CGRectMake(0, 140, self.view.frame.size.width, 30);
[PushBtn setTitle:@"Push" forState:(UIControlStateNormal)];
[PushBtn addTarget:self action:@selector(PushClick:) forControlEvents:(UIControlEventTouchUpInside)];
[self.view addSubview:PushBtn];

}
-(void)PushClick:(UIButton*)sender{

SecondViewController * secondVc = [[SecondViewController alloc]init];
//设置代理
secondVc.delegate =self;

[self.navigationController pushViewController:secondVc animated:YES];

}
//实现代理方法
-(void)viewController:(SecondViewController*)ViewController didPushVlaueWithInfo:(id)info{

textF.text = info;

}

(四)单例传值

单例可以保证某个类的实例在程序中是唯一的,便于进行资源和数据的共享。

单例的实现:
(1)新建一个普通的类,假设名字为People 在People.h中声明一个类方法,到时候使用该类方法(注意:一定是类方法,而不是实例方法)可以创建该类的唯一的一个实例

#import "Peopel.h"
@implementation People
{
  NSString *_eat;
 }
@property(nonatomic,retain)NSString *eat;
+(Peopel*)shareInstance;
@end

(2)在Peopel .m中需要实现sharedInstance方法和你其他的业务逻辑
#import "Peopel.h"
//static声明一个类的静态实例;
static Peopel instrance = nil;
@implementation Peopel
//使用类方法生成这个类唯一的实例
+(Peopel
)shareInstance{

if (instrance == nil) {
    instrance = [[super alloc]init];
  }
return instrance;

}
@end

注意:一定要声明一个static的静态变量。以后创建类的唯一实例就使用sharedInstance方法,而不是使用alloc ,init.

下面为单例传值的简单使用(完整代码):
FirstViewController
#import "FirstViewController.h"
#import "SecondViewController.h"
#import"Peopel.h"

@interface FirstViewController ()
{
  UITextField * textF;
}
@end

@implementation FirstViewController

- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor =[UIColor whiteColor];
[self creatUI];

}
//接收由第二个界面pop回时textF里的数据值
-(void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
textF.text=[Peopel shareInstance].eat;
}

-(void)creatUI{
textF = [[UITextField alloc]init];
textF.frame = CGRectMake(0, 100, self.view.frame.size.width, 30);
textF.borderStyle = UITextBorderStyleRoundedRect;
[self.view addSubview:textF];
UIButton * PushBtn = [UIButton buttonWithType:(UIButtonTypeSystem)];
PushBtn.frame = CGRectMake(0, 140, self.view.frame.size.width, 30);
[PushBtn setTitle:@"Push" forState:(UIControlStateNormal)];
[PushBtn addTarget:self action:@selector(PushClick:) forControlEvents:(UIControlEventTouchUpInside)];
[self.view addSubview:PushBtn];

}
-(void)PushClick:(UIButton*)sender{
//跳转下个界面的同时为单例属性赋值
 [[Peopel shareInstance]setEat:textF.text];
SecondViewController * secondVc = [[SecondViewController alloc]init];
[self.navigationController pushViewController:secondVc animated:YES];    
}
SecondViewController
#import "SecondViewController.h"
#import "Peopel.h"
@interface SecondViewController ()
{
UITextField * textF;
NSString * textFString;
}
@end

@implementation SecondViewController
-(void)viewWillDisappear:(BOOL)animated{
}
-(void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
textF.text = [Peopel shareInstance].eat;
}
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor redColor];
textF = [[UITextField alloc]init];
textF.frame = CGRectMake(0, 100, self.view.frame.size.width, 30);
textF.borderStyle = UITextBorderStyleRoundedRect;
textF.text = [Peopel shareInstance].eat;
[self.view addSubview:textF];
//返回按钮
UIButton * Backbtn = [UIButton buttonWithType:(UIButtonTypeSystem)];
Backbtn.frame  =CGRectMake(0, 140, self.view.frame.size.width, 30);
[Backbtn addTarget:self action:@selector(backClick:) forControlEvents:(UIControlEventTouchUpInside)];
[Backbtn setTitle:@"back" forState:(UIControlStateNormal)];
[self.view addSubview:Backbtn];
}

-(void)backClick:(UIButton*)sender{
//返回时为单例属性赋值
[Peopel shareInstance].eat = textF.text;
[self.navigationController popViewControllerAnimated:YES];
}

(五)通知传值

谁要监听值的变化,谁就注册通知 特别要注意,通知的接受者必须存在这一条件

1、注册通知
2、通知中心发送一条消息通知,其中name前后一定要一样
3、实现通知中心内部的方法,并实现传值
4、消息发送完,要移除掉。(页面将要消失的时候)

通知传值的简单代码如下:

代码为第二个界面传值到第一个界面的实现:

FirstViewController
#import "FirstViewController.h"
#import "SecondViewController.h"

@interface FirstViewController ()
{
  UITextField * textF;
}
@end

@implementation FirstViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor =[UIColor whiteColor];
[self creatUI];
/**
 adObserver:注册监听者,一般都是控制器本身去监听一个通知
 selector :当监听到通知的时候执行的方法
 name :通知的名字,要和发送的通知的对象的名字一致
 object: nil
 */
//注册监听者
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(ChangeTextFText:) name:@"ChangeValue" object:nil];

}
-(void)ChangeTextFText:(NSNotification*)notification{
NSDictionary * dic = notification.userInfo;
NSLog(@"%@",dic);
textF.text = dic[@"Value"];
}

-(void)creatUI{
textF = [[UITextField alloc]init];
textF.frame = CGRectMake(0, 100, self.view.frame.size.width, 30);
textF.borderStyle = UITextBorderStyleRoundedRect;
[self.view addSubview:textF];
UIButton * PushBtn = [UIButton buttonWithType:(UIButtonTypeSystem)];
PushBtn.frame = CGRectMake(0, 140, self.view.frame.size.width, 30);
[PushBtn setTitle:@"Push" forState:(UIControlStateNormal)];
[PushBtn addTarget:self action:@selector(PushClick:) forControlEvents:(UIControlEventTouchUpInside)];
[self.view addSubview:PushBtn];

}
-(void)PushClick:(UIButton*)sender{
SecondViewController * secondVc = [[SecondViewController alloc]init];
[self.navigationController pushViewController:secondVc animated:YES];
}

//移除控制器上所有监听的通知
-(void)dealloc{
[[NSNotificationCenter defaultCenter]removeObserver:self];
}
SecondViewController
#import "SecondViewController.h"

@interface SecondViewController ()
{

  UITextField * textF;
}
@end

@implementation SecondViewController
-(void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
}
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor redColor];
textF = [[UITextField alloc]init];
textF.frame = CGRectMake(0, 100, self.view.frame.size.width, 30);
textF.borderStyle = UITextBorderStyleRoundedRect;

[self.view addSubview:textF];

UIButton * Backbtn = [UIButton buttonWithType:(UIButtonTypeSystem)];

Backbtn.frame  =CGRectMake(0, 140, self.view.frame.size.width, 30);

[Backbtn addTarget:self action:@selector(backClick:) forControlEvents:(UIControlEventTouchUpInside)];
[Backbtn setTitle:@"back" forState:(UIControlStateNormal)];
[self.view addSubview:Backbtn];
}

-(void)backClick:(UIButton*)sender{
//发送通知
  [[NSNotificationCenter defaultCenter]postNotificationName:@"ChangeValue" object:nil userInfo:@{@"Value":textF.text}];
[self.navigationController popViewControllerAnimated:YES];
}

本讲完结:希望能给朋友们的学习带来帮助

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 207,248评论 6 481
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 88,681评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 153,443评论 0 344
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 55,475评论 1 279
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 64,458评论 5 374
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,185评论 1 284
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,451评论 3 401
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,112评论 0 261
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 43,609评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,083评论 2 325
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,163评论 1 334
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,803评论 4 323
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,357评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,357评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,590评论 1 261
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,636评论 2 355
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,925评论 2 344

推荐阅读更多精彩内容