1

Here's a quick and dirty question: I have a "main" view controller (VC) which is opened up from a parent VC, that uses a navigation controller. Then I have a "sub" VC that is opened (modal segue) from the "main" VC.

I have set a property in the main VC's interface:

@property (nonatomic) int myVar;

Then set it from the button's action that is touched to display the "sub"VC from the "main"VC's interface:

self.myVar=1;

I imported the mainVC.h in the subVC.h

Then at the viewDidLoad method of the subVC, I'm trying to access myVar's value, but can't do that with:

NSLog(@"Myvar is %i", ((mainVC*)self.parentViewController).myVar);

Which returns the value as 0.

And when I try presentingViewController method instead, I get an error (which did not cause the error when I pushed the segue instead of making it a modal:

[MainVC myVar]: unrecognized selector sent to instance

I'm trying to code for iOS 5, and needless to say that I'm still a noob. What am I missing?

Thanks!

rmaddy
  • 314,917
  • 42
  • 532
  • 579
user2292949
  • 65
  • 1
  • 4

1 Answers1

1

The parentViewController of the "sub" view controller is not the mainVC, it's the navigation controller. The mainVC is not accessible - for all you know, it may be deallocated to save memory.

If you need to pass data from the main controller to the sub controller on the segue, add an instance variable to the "sub" view controller, and set it in the prepareForSegue method:

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([[segue identifier] isEqualToString:@"open_sub"]) {
        subVC *sub = segue.destinationViewController;
        sub.myVar = 1;
    }
}
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • Thanks this worked. Just a note for near total noobs like me: You have to set the segue identifier to "open_sub" in the storyboard view and also import the subVC.h in the mainVC.h for this to work. However making the segue modal also caused another issue, the navigation bar is not there any more in the subVC, can't see that in the storyboardview either, how can I get it back? – user2292949 May 25 '13 at 08:15
  • 1
    @user2292949 Although you can make the navigation bar visible after a modal segue (see [this comment for details](http://stackoverflow.com/questions/9392744/difference-between-modal-and-push-segue-in-storyboards#comment18214174_9392936)) it rarely makes sense from the application's standpoint. See [this answer](http://stackoverflow.com/a/9392936/335858) for a brief explanation of when each type of segue is used. – Sergey Kalinichenko May 25 '13 at 09:40