Ios – Alternative ways to push view controllers with storyboard programmatically

iospushstoryboardviews

I'm looking for alternative ways to push view controllers instantiated on storyboard programmatically.
I've actually found two ways, that I use to go to the next view, but also to go back to the previous:

  1. using pushViewController:

    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle: nil]; 
    LocationWebView *lvc = [storyboard instantiateViewControllerWithIdentifier:@"LocationWebView"];
    [self.navigationController pushViewController:lvc animated:YES];
    
  2. performing Segue programmatically:

    [self performSegueWithIdentifier: @"SongSegue" sender: self];
    

Do you have some hints on alternatives and on the best way this operation should be performed? Note that I'm not referring to modal views.

Best Solution

Apple recommends using performSegueWithIdentifier:sender:someObject to programmatically perform segues. There are at least a couple of advantages to doing it this way:

  • Less of your own code means you're letting the framework do more of the work. If Apple comes up with some super-cool new visual effect for push segues, or improves performance, or fixes a bug in some future iOS release, your app can get it for free. And every line of code you write to do work the framework could be doing for you increases your chance of writing bugs.

  • More in IB can mean easier to change. If you decide you want to change all your push segues to modal segues, or some custom segue type where you do your own super-cool visual effect, you can select 'em all in IB and change the segue type with one click instead of hunting around in your code.


In addition, whether you use the first or second method, pushing a view controller in order to go "back" to a previous view controller won't work the way your users expect. When you push a SongViewController, it's added to the end of the navigation stack:

LocationViewController -> SongViewController

If you then push LocationViewController again to go "back":

LocationViewController -> SongViewController -> LocationViewController

If the user taps the back button in the navigation bar, they'll go back from the location view to the song view to the location view again. (Also, if you keep doing this, every "back" and "forward" will add to an ever-increasing chain of view controllers, which might lead to other trouble.)

Instead, you should let the navigation controller handle going back. It puts a button in the navigation bar for that purpose, which should handle most use cases. If you need to make your own control to go back, you can't do this in IB with iOS 5, but you can do it programmatically with the navigation controller's popViewControllerAnimated: method.