Search code examples
iosipadios5uipopovercontrolleruistoryboardsegue

Passing data on prepareForSegue for a Popover Segue: strange behavior in iOS 5


I noticed some strange behavior when passing data to a popover in iOS 5. The Popovers viewDidLoad method is called before prepareForSegue is called:

In Storyboard a segue connects a button of FirstViewController to PopoverViewController, which is embedded in a Navigation Controller.

For testing the two methods are logged:

/* FirstViewController.m */
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:@"showPopover"]) {
        NSLog(@"FirstViewController: prepareForSegue");
        UINavigationController *navigationController = segue.destinationViewController;
        PopoverViewController *popoverVC = (PopoverViewController *)navigationController.topViewController;
        popoverVC.myProperty = @"Data to be passed";
    }
}

and in the other ViewController:

/* PopoverViewController.m */
- (void)viewDidLoad {
    [super viewDidLoad];
    NSLog(@"PopoverViewController: viewDidLoad");
}

Under iOS 6 the behavior is as expected:

2013-02-25 09:03:53.747 FirstViewController: prepareForSegue
2013-02-25 09:03:53.751 PopoverViewController: viewDidLoad

Under iOS 5 viewDidLoad of the PopoverViewController is called before prepareForSegue:

2013-02-25 09:05:28.723 PopoverViewController: viewDidLoad
2013-02-25 09:05:28.726 FirstViewController: prepareForSegue

This is strange and makes it hard to pass data to the Popover which can be used in viewDidLoad. Is there any solution to this?


Solution

  • I solved the problem now using the viewWillAppear: method instead of viewDidLoad. I think this is the better method for configuring views anyway (as the view could be already loaded and the view should be configured on every appear).

    The viewWillAppear: method is loaded after the prepareForSegue in iOS 5 and iOS 6.

    However, for those needing viewDidLoad the solution suggested by tkanzakic is the one that works then.