您的位置:首页 > 移动开发 > IOS开发

iOS 五种传值方式

2016-05-27 13:13 357 查看
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"];

    

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: