在iOS開發(fā)過程中,界面間數據傳輸是最為基本的需求,蘋果公司為我們開發(fā)中提供了多種傳值方式娄琉,今天我們來談一談較為常用的五種方式次乓。
1、屬性傳值
2孽水、代理傳值
3票腰、block傳值
4、單例傳值
5匈棘、通知傳值
五種方式各有特點丧慈,在不同情況可以選擇使用不同的方式,接下來我們就說一說這五種傳值方式
一主卫、屬性傳值
一般來說如果從前一個界面往后一個界面進行傳值,屬性傳值是最簡單也是較為方便的一種鹃愤。
現在有兩個視圖控制器FirstViewController和SecondViewController簇搅,我們的需求是:在FirstViewController輸入一段內容,并將內容在SecondViewController中顯示软吐。這種情況就可以選擇屬性傳值瘩将,操作如下:
我們先在SecondViewController.h文件中設置一個接口,接收由第一個頁面?zhèn)鬟^來的內容
#import <UIKit/UIKit.h>
@interface SecondViewController : UIViewController
@property(nonatomic,strong)NSString *str;//傳值字符串
@end
在SecondViewController.m文件中創(chuàng)建一個label用來顯示接收到的內容
[super viewDidLoad];
self.view.backgroundColor = [UIColor orangeColor];
self.navigationItem.title = @"第二頁";
UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(30, 100, 314, 50)];
label.backgroundColor = [UIColor redColor];
label.text = _str;
[self.view addSubview:label];
}
接下來我們就可以利用在FirstViewController頁面利用傳值字符串str進行傳值了
//首先建立一個輸入框
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
self.navigationItem.title = @"第一頁";
self.firstTF = [[UITextField alloc]initWithFrame:CGRectMake(20, 200, 314, 50)];
self.firstTF.placeholder = @"請輸入....";
self.firstTF.borderStyle = UITextBorderStyleLine;
[self.view addSubview:_firstTF];
}
//然后進行頁面跳轉并傳值
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
self.secondCV = [SecondViewController new];
[self.navigationController pushViewController:_secondCV animated:YES];
_secondCV.str = _firstTF.text;
_secondCV.delegate = self;
}
這樣我們就實現了利用屬性從前往后的傳值需求凹耙。
代理傳值
剛剛我們介紹了利用屬性從前往后傳值姿现,那么如果開發(fā)過程中的需求是從后往前進行傳值呢?我們可以選擇代理傳值肖抱、block傳值或者單例傳值等等备典,這里我們先介紹下代理傳值。
我們仍使用上面的兩個頁面意述,但是開發(fā)需求變?yōu)椋涸赟econdViewController頁面輸入一段內容提佣,回調到FirstViewController上顯示
首先我們需要在SecondViewController.h文件中定義協議并聲明代理
#import <UIKit/UIKit.h>
//代理
@protocol secondViewControllerDelegate <NSObject>
-(void)pass:(NSString*)Volue;
@end
@interface SecondViewController : UIViewController
@property(nonatomic,strong)UITextField *secondTF;
@property(nonatomic,weak)id<secondViewControllerDelegate> delegate; //聲明代理
@end
在SecondViewController.m文件中創(chuàng)建輸入框吮蛹,并實現代理方法
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
self.navigationItem.title = @"第二頁";
//創(chuàng)建輸入框
_secondTF = [[UITextField alloc]initWithFrame:CGRectMake(30, 300, 314, 50)];
_secondTF.placeholder = @"再次輸入...";
_secondTF.borderStyle = UITextBorderStyleLine;
[self.view addSubview:_secondTF];
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
//跳轉頁面
[self.navigationController popViewControllerAnimated:YES];
//代理傳值
[_delegate pass:_secondTF.text];
}
然后我們需要FirstViewController.m文件中指定代理并實現代理方法
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
self.secondCV = [SecondViewController new];
[self.navigationController pushViewController:_secondCV animated:YES];
//指定代理
_secondCV.delegate = self;
}
//實現代理方法,接收傳過來的內容
-(void)pass:(NSString *)Volue{
_label .text = Volue;
}
//創(chuàng)建label顯示接收內容
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
_label = [[UILabel alloc]initWithFrame:CGRectMake(30, 100, 314, 50)];
_label.backgroundColor = [UIColor redColor];
[self.view addSubview:_label];
}
這樣我們就實現了使用代理方式從后往前進行傳值拌屏。
block傳值
基于其他幾種傳值方式潮针,block傳值是我使用較少的一種方式,在這里只是給大家簡單介紹下倚喂。
開發(fā)需求為:在SecondViewController頁面輸入一段內容每篷,回調到FirstViewController上顯示
首先我們要在SecondViewController.h文件中定義并聲明block,
#import <UIKit/UIKit.h>
//定義有參無返回值的匿名函數(傳遞字符串)
typedef void (^MyBlock)(NSString *);
@interface SecondViewController : UIViewController
//MRC:block的語義設置是copy,把block從棧區(qū)拷貝到堆區(qū),使用完之后,在dealloc釋放
//ARC:語義設置使用strong即可
@property(nonatomic,copy)MyBlock block;
@end
在SecondViewController.m文件中進行傳值
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
//block的調用
self.block(_textField.text);
[self.navigationController popViewControllerAnimated:YES];
}
在FirstViewController頁面接收傳遞過來的內容
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
SecondViewController *sencndVC = [SecondViewController new];
//通過回調將傳進來的字符串賦值給label
__block typeof(self)temp = self;//內存優(yōu)化
sencndVC.block = ^(NSString *string){
temp.Label.text = string;
};
[self showViewController:sencndVC sender:nil];
[sencndVC release];
}
這樣就完成了界面間的數值傳遞
單例傳值
單例傳值可以理解為定義一個全局靜態(tài)變量進行傳值端圈,我們同樣使用上面需求雳攘,將第二個頁面的內容傳入第一個頁面并顯示。
首先定義一個單例類枫笛,并創(chuàng)建一個對外接口吨灭。
#import <Foundation/Foundation.h>
@interface Datahandle : NSObject
@property(nonatomic,strong)NSString *passVolud;
+(instancetype)sharedHadle;
@end
在Datahandle.m文件中實現
#import "Datahandle.h"
@implementation Datahandle
static Datahandle *datahandle = nil;
//創(chuàng)建單例
+(instancetype)sharedHadle{
if (nil == datahandle) {
datahandle = [[Datahandle alloc]init];
}
return datahandle;
}
//也可以使用多線程創(chuàng)建
// static dispatch_once_t onceToken;
// dispatch_once(&onceToken, ^{
// datahandle = [[Datahandle alloc]init];
// });
//
// return datahandle;
@end
在第二個頁面secondViewController.m文件中創(chuàng)建輸入框并在頁面跳轉時將輸入框內容傳值
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
self.secondTF = [[UITextField alloc]initWithFrame:CGRectMake(30, 300, 314, 50)];
_secondTF.borderStyle = UITextBorderStyleLine;
[self.view addSubview:_secondTF];
self.navigationItem.title = @"第二頁";
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
[self.navigationController popViewControllerAnimated:YES];
Datahandle *data = [Datahandle sharedHadle];
data.passVolud = _secondTF.text;
NSLog(@"%@",data.passVolud);
}
在第一個頁面接收并顯示內容,這里有一點需要注意從第二個頁面?zhèn)骰貋淼臅r候,傳值有個加載順序,只能在即將加載中顯示
-(void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
Datahandle *data = [Datahandle sharedHadle];
//接收字符串并顯示
_firstTF.text = data.passVolud;
}
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
self.firstTF = [[UITextField alloc]initWithFrame:CGRectMake(20, 300, 314, 50)];
_firstTF.borderStyle = UITextBorderStyleLine;
[self.view addSubview:_firstTF];
self.navigationItem.title = @"第一頁";
}
通知傳值
在各控制器之間傳值除了代理模式外刑巧,通知也是較為快捷喧兄,方便的方式之一。
我們假定這樣一個場景啊楚,有兩個頁面吠冤,需要從第二個頁面?zhèn)鬟f數值到第一個頁面,這時我們就可以選用通知模式恭理。
首先我們在第二個頁面創(chuàng)建一個按鈕拯辙,點擊按鈕跳轉頁面并發(fā)送通知。
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor orangeColor];
self.navigationItem.title = @"第二頁";
//創(chuàng)建按鈕
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.backgroundColor = [UIColor greenColor];
button.frame = CGRectMake(100, 100, 100, 80);
[button addTarget:self action:@selector(abc:) forControlEvents:UIControlEventTouchDown ];
[self.view addSubview:button];
}
-(void)abc:(UIButton *)sender{
[self.navigationController popToRootViewControllerAnimated:YES];
//創(chuàng)建字典
NSDictionary *dict = [NSDictionary dictionaryWithObject:@"passVole" forKey:@"key"];
//發(fā)送通知
[[NSNotificationCenter defaultCenter]postNotificationName:@"volue" object:nil userInfo:dict];
}
在第一個頁面添加觀察者颜价,用來監(jiān)聽通知事件
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor redColor];
//注冊通知(等待接收消息)
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(volue:) name:@"volue" object:nil];
}
-(void)volue:(NSNotification *)sender{
//打印通知傳過來的數值
NSLog(@"%@",sender.userInfo[@"key"]);
}
通知就是這么簡單涯保,發(fā)送通知,接收通知周伦,簡單幾步就實現了界面間的通信夕春。但是使用通知時有一點必須注意,使用完之后必須及時移除专挪,避免造成混亂及志。