传值

来源:互联网 发布:方维社区o2o系统 源码 编辑:程序博客网 时间:2024/05/19 19:40

方法一:属性传值

第一个视图(根视图):FirstViewController

在该视图下设置的button方法里面

-(void)buttonAction:(UIButton *)button

{

SecondViewController * secondVC = [[SecondViewControlleralloc] init];

[self.navigationControllerpushViewController:secondVC animated:YES];

将此时的button标题传入第二个视图的属性中去

secondVC.passValue = button.currentTitle;

}

第二个视图: SecondViewController

在想要获得值的那个视图中设置对应的属性 这里面以NSString为例

@property(nonatomic ,retain)NSString * passValue;

在- (void)viewDidLoad中要进行label的传值

label.text = self.passValue;(黄色为第二个视图的label)

 

方法二:单例传值

1.   首先创建一个类继承与NSObject

2.   在.h中声明自己的初始化方法和需要传值的对应属性

//1.单例是一个类的对象

//2.单例在整个程序中有且只有一个(对象)只能够赋值一次  可以没有

//3.单例一般使用加号+方法创建对象

获取单例的实例

AppDelegate * appdelegate =[[UIApplicationsharedApplication] delegate];

 

+ (Singleton *)shareInstance;//单例的创建方法

//存储一个字符串数据

@property(nonatomic,retain)NSString * string;

3.在.m中实现方法

+ (Singleton *)shareInstance

{

   

    //只有一次使用static创建一个空指针

    //const 是不能改变的

    //这样一但赋值就没办法再次赋值了只能够调用;

    static DataBaseHandler * handler = nil;

   

//保证线程安全的情况下 进行一次   手打dispatch_once  GCD那个

    static dispatch_once_t onceToken;

    dispatch_once(&onceToken,^{

        handler =[[DataBaseHandleralloc] init];

 

});

    return handler;

   

}

3.   还是在第一个视图和第二个视图之间传值

第一个视图的button方法:

 -(void)buttonAction:(UIButton *)button

{

    SecondViewController * secondVC = [[SecondViewControlleralloc] init];

    [self.navigationControllerpushViewController:secondVC animated:YES];

    //利用 +号方法创建一个单例对象

    Singleton * s = [SingletonshareInstance];  

    //利用单例给单例的属性传值

    s.string = [button currentTitle];

    [secondVC release]; 

}

第二个视图的ViewDidLoad

//利用单例获取想要的值

    Singleton * s2  = [SingletonshareInstance];  

    label.text = s2.string;

 

 

 

 

 

应用于反向传值

方法一:代理传值(核心,关键)

1.指定协议

//3视图控制器定义一个协议

@protocol thirdDelegate <NSObject>

//制定的协议方法

- (void)aa:(NSString *)value;

@end

2.设置代理属性

@property(nonatomic ,assign)id<thirdDelegate> delegate;

3.在需要发送数据的视图3的button中设置代理实现方法

- (void)buttonAction:(UIButton *)button

{

    //在推出之前,让自己的代理执行方法

    //目的给代理人(A)传第一个参数

    [self.delegateaa: ((UITextField *)[self.viewviewWithTag:10000]).text];

   

    [self.navigationControllerpopViewControllerAnimated:YES];

  

}

4.   在视图2(即将接受数据的视图).h中导入视图3的.h文件,并且要签署视图3所指定的协议.

#import <UIKit/UIKit.h>

#import "ThirdViewController.h"

@interface SecondViewController :UIViewController<thirdDelegate>

视图2的button方法中将自己设置为视图3的代理:

-(void)buttonAction:(UIButton *)button

{

    ThirdViewController * thirdVC = [[ThirdViewControlleralloc] init];

   

    [self.navigationControllerpushViewController:thirdVC animated:YES];

     

    //设置第三个页面的代理人

   

    thirdVC.delegate = self;

   

    [thirdVC release];

   

}

5.          在视图2中实现代理放法

- (void)aa:(NSString *)value

{

    ((UILabel *)[self.viewviewWithTag:10000]).text = value;

   

}

0 0
原创粉丝点击