4

Lets say I have two viewcontrollers ViewControllerA and ViewControllerB when I press a button from viewcontrollerA it is pushing to viewControllerB. However before pushing I want to set a property of viewControllerB from viewControllerA. But all I get is nil value when I check the variable from viewControllerB. What I do is;

In ViewControllerA:

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

but the thing is I also want to reach it from viewControllerB but I get nil for the variable.

In ViewControllerB:

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

But when I try to check the value in viewDidLoad method of ViewControllerB

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

Probably I miss a small point I could not figure out. Any help would be awesome. Thanks.


Edit: I am using storyboards. I push with the following code:

    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle: nil];
    lvc = [storyboard instantiateViewControllerWithIdentifier:@"mainManu"];
    [self.navigationController pushViewController:lvc animated:YES];
jszumski
  • 7,430
  • 11
  • 40
  • 53
death7eater
  • 1,094
  • 2
  • 14
  • 35

1 Answers1

7

If you use VCB = [[ViewControllerB alloc]init]; but push via Storyboard, then VCB is not the same ViewController used in Storyboard. Try this:

 - (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
     if ([[segue identifier] isEqualToString:@"yourSegueName"]) {
         ViewControllerB *vc = [segue destinationViewController];
         [vc setPropertyOfViewControllerB:@"foo"];
     }  
}
xapslock
  • 1,119
  • 8
  • 21
  • yes I see your point but the thing is I dont want to use that delegate method because in my application when a button pressed first I want make some assignments (data coming from a webservice) so I have to be sure that all the data is collected and assigned to the properties then i want to push. but in your answer it pushes immediately. – death7eater Apr 17 '13 at 15:20
  • No, prepareForSegue: will automatically called before every VC will be pushed. You can do your stuff, webservice, etc. and then call [self performSegueWithIdentifier:@"yourSegueName" sender:self]; – xapslock Apr 17 '13 at 15:24
  • I think I solved the problem with your approach I just added [vc setPropertyOfViewControllerB:@"foo"]; in my version of pushing and it worked...thanks – death7eater Apr 17 '13 at 15:25