ViewController之间传值

来源:互联网 发布:我欲封天时装进阶数据 编辑:程序博客网 时间:2024/06/15 15:51

1.属性/方法

两个页面A,B;A转到B页面

//在A页面,跳转时    BViewController *bPage = [[BViewController alloc] init];    //B页面的textString公开属性接受值    bPage.textString = @"test one";    //navigationController控制跳转页面    [self.navigationController pushViewController:bPage animated:YES];  
  //B页面,这时textString已被赋值,页面内任何位置都可使用它- (void)viewDidLoad {    [super viewDidLoad];    //显示传递的值    _label.text = _textString;    }

2.Block
传递方式可理解为:在当前页面可接受其他页面的值;
相当于回调函数

//在A页面,给B页面passValue属性赋值,值是一段代码块 ,“^“是标示符,参数根据定义的来;参数值就是来自B页面的值;在方法内将值显示在A页面    BViewController *bPage = [[BViewController alloc] init];    bPage.passValue=^(NSString *textStr){        _label.text =textStr;    };

下面我们看看在B页面里是怎么定义的

//.h文件中定义typedef void(^PassingValueBlock)(NSString *);@interface MyDetailViewController : @property(nonatomic,copy) PassingValueBlock passValue;@end//.m文件中传值,根据定义的参数传字符串_passValue(@"send block message");

3.UINotificationCenter通知传值
-发送方:

//"hello"为双方定义的通知名称;object放传递的值    [[NSNotificationCenter defaultCenter] postNotificationName:@"hello" object:@"Notification message test"];
    // 取消通知    [[NSNotificationCenter defaultCenter]removeObserver:self                                                   name:@"hello"                                                 object:nil];

-接收方:

//接受"hello"的通知;selector添加自定义接受方法名,接受到通知就会执行该方法    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(notificationMessage:) name:@"hello" object:nil];//接受方法-(void)notificationMessage:(NSNotification *)notify{    id obj = [notify object];//获取到传递的对象    _label.text = obj;//显示为字符串}

4.静态变量传值

//static修饰变量,定义赋值方法(如setStaticString)传值,定义获取方法(如getStaticString)得值static NSString * staticString = @"This is static string";
0 0