Nicer Segue Preparation With Storyboards

When we started developing the iOS app for Braid, a decision I made early on was to use Storyboards. If you’re not familiar, storyboards are a way to create iOS user interfaces visually and draw connections between the different screens in your app. In storyboard-speak, each screen is referred to as a “scene,” and the transitions between each scene is called a “segue.” Storyboards are a fantastic feature for a couple of reasons, including that when using storyboards you can set up static and dynamic table views visually, drag and drop container view controllers and get a visual picture of what you’re entire app looks like.

One part of coding with storyboards has always bothered me though — the strange way that Apple’s example code shows how to set up a view controller before a transition (setting a delegate, detail object, etc):

The string comparison felt a little gross to me, and if you have a lot of different segues, the if/else in this method could get long pretty fast, even if you’re breaking out what happens in each condition into it’s own method. If you do end up writing a method for each segue, all of those -[prepareForSomethingWithSegue:sender] methods could get repetitive pretty fast.

A nicer way is to use a block for each segue you need to prepare and to encapsulate that into it’s own class, which I did. The class is called BRLSeguePreparationController and makes it very simple to deal with preparing for segue’s in this way.

  1. Create a BRLSeguePreparationBlock for each segue you need to prepare for.
  2. Set them using -[BRLSegueController setPreparationBlock:forSegueIdentifier:]
  3. Call -[BRLSeguePreparationController prepareSegue:identifier:] from your view controllers prepareForSegue:sender: method.

Here’s an example:

I’ve given the class it’s own GitHub repo and an MIT license, so use it in your own projects. If you make any improvements, make sure you add a pull request on GitHub. If you find the class useful, please check out my companies website to find out what we’re working on, and download our Passbook pass from there to keep up to date when our app comes out.

Jumping to Protocol Definitions With Pragma Mark

Using pragma marks to organize source files is one sign that the person who wrote the class put a little bit of care into what they’re doing, but they can actually be more useful than just a way of breaking up an implementation file.

My favorite trick is to use how I name my pragmas to jump to protocol definitions more quickly. I always use a pragma mark before the implementation of a protocol in my source, and in most of the code I’ve other people write, they do something like this:

A better way is to use the actual name of the protocol you’re implementing instead, like this:

Now, if you command+click on that Xcode will jump right to the protocol definition, and option+double-click will take you straight to it’s documentation.