在iOS開發過程中,界面間數據傳輸是最為基本的需求,蘋果公司為我們開發中提供了多種傳值方式,今天我們來談一談較為常用的五種方式。
1、屬性傳值
2、代理傳值
3、block傳值
4、單例傳值
5、通知傳值
五種方式各有特點,在不同情況可以選擇使用不同的方式,接下來我們就說一說這五種傳值方式
一、屬性傳值
一般來說如果從前一個界面往后一個界面進行傳值,屬性傳值是最簡單也是較為方便的一種。
現在有兩個視圖控制器FirstViewController和SecondViewController,我們的需求是:在FirstViewController輸入一段內容,并將內容在SecondViewController中顯示。這種情況就可以選擇屬性傳值,操作如下:
我們先在SecondViewController.h文件中設置一個接口,接收由第一個頁面傳過來的內容
#import <UIKit/UIKit.h>
@interface SecondViewController : UIViewController
@property(nonatomic,strong)NSString *str;//傳值字符串
@end
在SecondViewController.m文件中創建一個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;
}
這樣我們就實現了利用屬性從前往后的傳值需求。
代理傳值
剛剛我們介紹了利用屬性從前往后傳值,那么如果開發過程中的需求是從后往前進行傳值呢?我們可以選擇代理傳值、block傳值或者單例傳值等等,這里我們先介紹下代理傳值。
我們仍使用上面的兩個頁面,但是開發需求變為:在SecondViewController頁面輸入一段內容,回調到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文件中創建輸入框,并實現代理方法
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
self.navigationItem.title = @"第二頁";
//創建輸入框
_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;
}
//創建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傳值是我使用較少的一種方式,在這里只是給大家簡單介紹下。
開發需求為:在SecondViewController頁面輸入一段內容,回調到FirstViewController上顯示
首先我們要在SecondViewController.h文件中定義并聲明block,
#import <UIKit/UIKit.h>
//定義有參無返回值的匿名函數(傳遞字符串)
typedef void (^MyBlock)(NSString *);
@interface SecondViewController : UIViewController
//MRC:block的語義設置是copy,把block從棧區拷貝到堆區,使用完之后,在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;//內存優化
sencndVC.block = ^(NSString *string){
temp.Label.text = string;
};
[self showViewController:sencndVC sender:nil];
[sencndVC release];
}
這樣就完成了界面間的數值傳遞
單例傳值
單例傳值可以理解為定義一個全局靜態變量進行傳值,我們同樣使用上面需求,將第二個頁面的內容傳入第一個頁面并顯示。
首先定義一個單例類,并創建一個對外接口。
#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;
//創建單例
+(instancetype)sharedHadle{
if (nil == datahandle) {
datahandle = [[Datahandle alloc]init];
}
return datahandle;
}
//也可以使用多線程創建
// static dispatch_once_t onceToken;
// dispatch_once(&onceToken, ^{
// datahandle = [[Datahandle alloc]init];
// });
//
// return datahandle;
@end
在第二個頁面secondViewController.m文件中創建輸入框并在頁面跳轉時將輸入框內容傳值
- (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);
}
在第一個頁面接收并顯示內容,這里有一點需要注意從第二個頁面傳回來的時候,傳值有個加載順序,只能在即將加載中顯示
-(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 = @"第一頁";
}
通知傳值
在各控制器之間傳值除了代理模式外,通知也是較為快捷,方便的方式之一。
我們假定這樣一個場景,有兩個頁面,需要從第二個頁面傳遞數值到第一個頁面,這時我們就可以選用通知模式。
首先我們在第二個頁面創建一個按鈕,點擊按鈕跳轉頁面并發送通知。
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor orangeColor];
self.navigationItem.title = @"第二頁";
//創建按鈕
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];
//創建字典
NSDictionary *dict = [NSDictionary dictionaryWithObject:@"passVole" forKey:@"key"];
//發送通知
[[NSNotificationCenter defaultCenter]postNotificationName:@"volue" object:nil userInfo:dict];
}
在第一個頁面添加觀察者,用來監聽通知事件
- (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"]);
}
通知就是這么簡單,發送通知,接收通知,簡單幾步就實現了界面間的通信。但是使用通知時有一點必須注意,使用完之后必須及時移除,避免造成混亂。