iphone开发:如何设置另一个viewController的属性然后到达它

时间:2013-04-17 14:58:59

标签: iphone ios objective-c uiviewcontroller

让我说我有两个viewcontrollers ViewControllerAViewControllerB当我按下viewcontrollerA按钮时它正推送到viewControllerB。但是在推送之前,我想从viewControllerB设置viewControllerA的属性。但是当我从nil检查变量时,我得到的是viewControllerB值。我做的是;

ViewControllerA

VCB = [[ViewControllerB alloc]init];
[VCB setPropertyOfViewControllerB:someString];
NSLog(@"value: %@", VCB.PropertyOfViewControllerB); // Here I observe the correct value so I set successfully

但问题是我也希望从viewControllerB到达它,但我得到nil变量。

ViewControllerB

//I already defined in h file as property
NSString *PropertyOfViewControllerB;
@property(nonatomic, retain) NSString *PropertyOfViewControllerB;

但是当我尝试检查ViewControllerB的viewDidLoad方法中的值时

NSLog(@"value: %@", PropertyOfViewControllerB);//here I get null not the value I set at viewControllerA

可能我想念一个我无法弄清楚的小点。任何帮助都是极好的。感谢。


编辑:我正在使用故事板。我按下面的代码推送:

    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle: nil];
    lvc = [storyboard instantiateViewControllerWithIdentifier:@"mainManu"];
    [self.navigationController pushViewController:lvc animated:YES];

1 个答案:

答案 0 :(得分:7)

如果你使用VCB = [[ViewControllerB alloc]init];但是通过Storyboard推送,那么VCB与Storyboard中使用的ViewController不同。 试试这个:

 - (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
     if ([[segue identifier] isEqualToString:@"yourSegueName"]) {
         ViewControllerB *vc = [segue destinationViewController];
         [vc setPropertyOfViewControllerB:@"foo"];
     }  
}