1. 程式人生 > >iOS 五種傳值方式

iOS 五種傳值方式

iOS 有五種傳值方式

一.屬性傳值

屬性傳值最為簡單,但是比較單一,只能從一個檢視傳至另一個檢視,

屬性傳值第一步需要用到什麼型別就定義什麼樣的屬性

新建兩個檢視控制器RootViewController和SecondViewController,從一個頁面傳至第二個頁面

(1).在第二個頁面建立屬性,用來接收值

 @property(nonatomic,strong)NSString *string;

(2). 在第一個頁面檢視控制器RootViewController點選button跳轉頁面的響應事件中.給第二個頁面的屬性賦值
     secondVC.string =self.rootV.textfield.text;

(3).在SecondViewController中賦值即可

     self.secondV.textfield.text= self.string;

二.block傳值

block 傳值只能單方面傳值,從SecondViewController向RootViewController中傳值

block傳值第一步: 在RootViewController寫一個block
typedef void(^sendMessageBlock) (NSString *str);

block傳值第二步:(block 注意用:copy),block是匿名函式
@property(nonatomic,copy)sendMessageBlock block;

block傳值第三步:寫一個傳值方法(引數是寫自己的block)
-(void)sendMessage:(sendMessageBlock)block;

block傳值第四部:實現自定義的方法
-(void)sendMessage:(sendMessageBlock)block{
    self.block =block;
}
block傳值第五步:
    self.block(self.secondV.textfield.text);
block傳值第六部:在RootViewController中賦值
    [secondVC sendMessage:^(NSString *str) {
        self.rootV.textfield.text =str;
    }];

三.代理傳值

//代理傳值第一步:在SecondViewController寫協議(包括方法)
@protocol sendMessageDelegate <NSObject>

-(void)sendMessage:(NSString *)string;

@end

//代理傳值第二步:在第二個頁面寫一個遵循協議的屬性
@property(nonatomic,weak)id<sendMessageDelegate>delegate;

//代理傳值第三步:調方法傳值
        [self.delegate sendMessage:self.secondV.textfield.text];

//代理傳值的第四部:遵循協議
@interface RootViewController ()<sendMessageDelegate>

 //代理傳值的第五部:設定代理.(給第二個頁面設定代理)
    secondVC.delegate =self;

//代理傳值第六步:實現方法
-(void)sendMessage:(NSString *)string

{
    self.rootV.textfield.text =string;  
}

四.單例傳值

單例可以雙向傳值

新建一個繼承與UIView的檢視,命名為Single

@interface Single : NSObject

@property(nonatomic,strong)NSString *sendMessage;

+(Single *)shareSingle;

在Single.m中實現

#import "Single.h"

static Single *share = nil;

@implementation Single

+(Single *)shareSingle{
    @synchronized(self) {
        if (share == nil) {
            share = [[Single alloc]init];
        }
        return share;
    }
}
@end

在RootViewController中定義

  Single *sing = [Single shareSingle];
    sing.sendMessage = self.textField.text;

在SecondViewController中定義

Single *sing = [Single shareSingle];
   _secondV.textField.text = sing.sendMessage;

五.通知

在SecondViewController中新建通知

    NSDictionary *dic = [[NSDictionary alloc]initWithObjectsAndKeys:self.secondV.textField.text,@"textOne1", nil];
    NSNotification *notification = [NSNotification notificationWithName:@"tongzhi" object:nil userInfo:dic];
    //通過通知中心傳送通知
    [[NSNotificationCenter defaultCenter]postNotification:notification];
   
在RootViewController中註冊通知

    //註冊通知
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(tongzhi:) name:@"tongzhi" object:nil];

-(void)tongzhi:(NSNotification *)text{
    
    self.textField.text = text.userInfo[@"textOne1"];
    
}