Storyboard Constants

##Automate all the things

Storyboards can really speed up development but a problem I run into over and over again is working with identifiers that are set in the storyboard and referenced in code.

#Problem

Let’s take the example of making a segue:

You create a segue and then assign it an identifier in the storyboard… and that’s the problem. The identifier is defined in the storyboard, which leaves me with plenty of opportunities to mess up referencing the segue in code.

My normal strategy is to create a constants file that would have a constant with the value of each of these identifiers, which starts to look like the following (forgive the naming):

StoryboardConstants.h

extern NSString * const PSBMasterToDetail;
extern NSString * const PSBMasterToSettings;

This works for me and I’m happy, but it seems like a lot of manual graft and can become tiresome to maintain especially in a young project with lots of development spikes. It’s also still very possible to make typos and mess up these declarations or for them to become out of sync with the storyboard.

#Automation

I got to thinking about this problem and two things stood out

  1. I don’t like doing things manually and
  2. I don’t like that it is so easy to misspell a constant when swapping between storyboard and code (yes I am aware copy and paste exists).

So I started tinkering and I’ve come up with a rough tool that I’ve cunningly named sbconstants.

My automation idea is that you add a build script that will extract constants from your storyboards and then dump them into a file.

Grab it with

sudo gem install sbconstants

My first effort has a UI like this (command line app)

% sbconstants -h
Usage: DESTINATION_FILE [options]
    -p, --prefix=<prefix>            Only match identifiers with <prefix>
    -s, --source-dir=<source>        Directory containing storyboards
    -q, --queries=<queries>          YAML file containing queries
    -d, --dry-run                    Output to STDOUT
    -v, --verbose                    Verbose output

To get this working on a project the sbconstants gem needs to be installed to the system Ruby and then we need to call the executable from a build script. An example call would look like this

sbconstants MyApp/Constants/PASStoryboardConstants.h

NB The argument is the destination file to dump the constants into - this needs to be added manually

Every time this project is built it will parse the storyboard files and pull out any constants and then dump them into PASStoryboardConstants.(h|m). This of course means that PASStoryboardConstants.(h|m) should not be edited by hand as it will just be clobbered any time we build.

The output of running this tool will look something like this:

PASStoryboardConstants.h

// Auto generated file - any changes will be lost

#pragma mark - tableViewCell.reuseIdentifier
extern NSString * const PSBAwesomeCell;  

#pragma mark - segue.identifier
extern NSString * const PSBMasterToDetail;  
extern NSString * const PSBMasterToSettings;  

PASStoryboardConstants.m

// Auto generated file - any changes will be lost

#import "PASStoryboardConstants.h"

#pragma mark - tableViewCell.reuseIdentifier
NSString * const PSBAwesomeCell = @"PSBAwesomeCell";

#pragma mark - segue.identifier
NSString * const PSBMasterToDetail = @"PSBMasterToDetail";
NSString * const PSBMasterToSettings = @"PSBMasterToSettings";

The constants are grouped by where they were found in the storyboard xml e.g. segue.identifier. This can really help give you some context about where/what/when and why a constant exists.

##More options

Options are fun and there are a few to play with - most of these options are really only any good for debugging.

###--prefix -p, –prefix= Only match identifiers with

Using the prefix option you can specify that you only want to grab identifiers that start with a certain prefix, which is always nice.

###--source-dir -s, –source-dir= Directory containing storyboards

If you don’t want to run the tool from the root of your app for some reason you can specify the source directory to start searching for storyboard files. The search is recursive using a glob something like <source-dir>/**/*.storyboard

###--dry-run -d, –dry-run Output to STDOUT

If you just want to run the tool and not write the output to a file then this option will spit the result out to $stdout

###--verbose -v, –verbose Verbose output

Perhaps you want a little more context about where your identifiers are being grabbed from for debugging purposes. Never fear just use the --verbose switch and get output similar to:

sample output

#pragma mark - viewController.storyboardIdentifier
//
//    info: MainStoryboard[line:43](viewController.storyboardIdentifier)
// context: <viewController restorationIdentifier="asd" storyboardIdentifier="FirstViewController" id="EPD-sv-vrF" sceneMemberID="viewController">
//
NSString * const FirstViewController = @"FirstViewController";

###--queries -q, –queries= YAML file containing queries

Chances are I’ve missed some identifiers to search for in the storyboard. You don’t want to wait for the gem to be updated or have to fork it and fix it. Using this option you can provide a YAML file that contains a description of what identifers to search for. The current one looks something like this (NB this is a great starting point for creating your own yaml):

queries

---
segue: identifier
tableViewCell: reuseIdentifier
view: restorationIdentifier
? - navigationController
  - viewController
  - tableViewController
: - storyboardIdentifier
  - restorationIdentifier
  

This looks a little funky but it’s essentially groups of keys and values (both the key and the value can be an array). This actually gets expanded to looks for

+----------------------+-----------------------+
|         node         |      attribute        |
+ ---------------------+-----------------------+
| segue                | identifier            |
| tableViewCell        | reuseIdentifier       |
| view                 | restorationIdentifier |
| navigationController | storyboardIdentifier  |
| viewController       | storyboardIdentifier  |
| tableViewController  | storyboardIdentifier  |
| viewController       | restorationIdentifier |
| navigationController | restorationIdentifier |
| tableViewController  | restorationIdentifier |
+----------------------+-----------------------+

#Conclusion

I’m not sure if this tool will be of any use to anyone but for the projects I’ve been tinkering with it seems to work pretty well leaving me confident that my storyboard identifier’s will not go out of sync with how they are referenced in code.

If anyone does use this and they like it or they have any issues please report it to me so I can get it fixed up and improve my own workflow.

Blockception

Blocks are a lot of fun and they can make some really slick API’s. It’s also worth noting that blocks also require a fair amount of overhead to get used to how they work and how to use them. I would consider myself fairly competent with blocks but this confidence can lead to potentially “clever code”. “Clever code” is sometimes hard to maintain depending on how clever you was feeling at the time of writing it.

In this post I intend to cover one such bit of “clever code” and how it could be implemented differently to compare and contrast the results.

##Using delegates

I’ll start by looking at the implementation I didn’t actually do and then step by step arrive at the solution I initially wrote. From here I can compare and contrast and see which solution I should have done.

The sequence of events looks something like this

Delegate Implementation

So at this point we have a working solution and all is good.

The code to loop over the points looks something like this

View.m

for (int i = 0; i < self.dataSource.numberOfPoints; i++) {
  CGPoint point = [self.dataSource pointAtIndex:i];
  // convert point and build path
}

Something about asking for the count and then iterating over it seems a little awkward to me, I’d much rather the thing that held this information (the model) kept it’s data a little closer to it’s chest and iterated over itself passing out the points. There are two options here

  1. Implement NSFastEnumeration
  2. Add some kind of enumerator

I prefer the second option

##Block enumeration

The block enumeration ends up looking like this:

Model.m

- (void)enumeratePointsWithBlock:(void (^)(CGPoint point, NSUInteger idx, BOOL *stop))block;
{
  BOOL exitLoop = NO;
  
  for (int i = 0; i < self.locationCount; i++) {
    block(CGPointMake(self.locations[i], self.locations[i]), i, &exitLoop);
    if (exitLoop) {
      break;
    }
  }
}

This creates an issue - for this to work I would have to call this enumerator in the View. I could simply bypass the Controller and pass the View a reference to the Model but I don’t like the sound of this. The more pressing issue is that the Model works in a different coordinate space to the View and the Controller is currently handling this conversion.

To get this to work I’ll need to restructure to look like this

Enumeration Implementation

This diagram actually looks simpler. There’s a couple of things to now note

  • There are new required methods that need to be called and in a specific order beginDrawing and commitDrawing
  • The path building now occurs over a series of method calls to View

Straight away I can see a way to remove the requirement to call beginDrawing and commitDrawing at this level by using a block that wraps this up in a tasty sandwich.

##Sandwich block

The sandwich block puts the interesting code that changes as the sandwich filler and the boilerplate as the bread, which will look like this:

Model.m

- (void)drawWithBlock:(void (^)(void))block;
{
  [self beginDrawing];
  block();
  [self commitDrawing];
}

This hides a message in our sequence diagram and removes the requirement to remember to call beginDrawing and commitDrawing.

Sandwich Implementation

So actually getting the View to draw can now all be kicked off from the Controller and would look something like this:

Controller.m

- (void)drawGraph;
{
  [self.view drawWithBlock:^{
    [self.model enumeratePointsWithBlock:^(CGPoint point){
      [self.view buildWithPoint:[self convertPoint:point]];
    }];
  }];
}

Now at this point we can look at the public interfaces of the MVC trio and it’s looking quite smart

Model.m

- (void)enumeratePointsWithBlock:(void (^)(CGPoint point, NSUInteger idx, BOOL *stop))block;

Controller.m

- (void)drawGraph;

View.m

- (void)drawWithBlock:(void (^)(void))block;
- (void)buildWithPoint:(CGPoint)point;

Every object appears to be toeing the MVC line, although I see a method that probably doesn’t belong in the public API. The View now has the method -[View buildWithPoint:], which only makes sense in the context of drawing, it’s not clear by looking at the public interface what this method does or in what context to call it.

So here’s another opportunity to use a block, this final implementation brings us to the title of this post Blockception. We now end up with a block in a block which calls a block passed in by the first block.

This ends up looking like the following:

View.h

typedef void (^draw_point_b)(CGPoint drawPoint);

Controller.m

- (void)drawGraph;
{
  [self.view drawWithBlock:^(draw_point_b drawBlock) {
    [self.model enumeratePointsWithBlock:^(CGPoint point){
      drawBlock([self convertPoint:point]);
    }];
  }];
}

The drawBlock essentially takes the functionality of the old -[View buildWithPoint:] and passes it straight where it is actually needed.

##Differences

###Delegate Implementation

The delegate implementation requires a fair amount more code to write. A @protocol needs to be introduced to allow the view to have a dataSource. There is also the methods on the controller that conform to this protocol and end up proxying them straight onto the Model and then slightly changing the result.

Looking at the initial sequence diagram there seems to be more back and forth of messages to achieve the same result than where we end up.

The Model is required to expose how many elements it has and then allow an external object to iterate over that in a way which is out of it’s control.

###Block Implementation

The block implementation has 2 of my favorite ways to use blocks, which are for enumeration and wrapping code.

The public interfaces for all the objects expose very little about themselves, which is always nice.

There are considerably more awkward carets and curly braces, which can be confusing.

##Conclusion

Looking back at both solutions the delegate technique can be easier to fully grasp and follow along. The block implementation completely failed my “can I explain how this is working to a colleague in one attempt” rule, but I feel the delegate setup would only fair slightly better.

The reason I originally implemented this using blocks over delegates was purely because I had the block enumeration on the Model and this was the only way I could think to make it all fit.

I do like how the block implementation hides away any gory details about the structures of the objects but the very fact that I’ve had to write a blog post about this probably means it’s too clever. I think the answer to “which is better?” is we’ll have to wait and see how the block implementation stands up over time.

Simple Developer Happiness gains

Doing repetitive work over and over is always frustrating. Thankfully good developers automate the things they do or find other people who have done the hard work already.

You don’t have to be amazing at scripting to hack something together that can really make things easier. People often stray away from tech they are not used to but it’s worth just “giving things a go” to see how you get on.

Here’s a simple Ruby script that I use several times a day when working with my Xcode projects.

##The problem

I often start from or find myself on the command line using Git or navigating my projects. I also like to use CocoaPods to deal with project dependencies. This results in an annoying issue when opening Xcode, for projects that use CocoaPods you need to open the *.xcworkspace and for projects that don’t use CocoaPods you need to open *.xcodeproj. I also do not enjoy using the graphical File->Open….

##The solution

Make a little script to deal with the inconsistency and allow me to open projects quickly form the command line.

some-where-in-$PATH/xopen

#!/usr/bin/env ruby

require 'shellwords'

proj = Dir['*.xcworkspace'].first
proj = Dir['*.xcodeproj'].first unless proj

if proj
  puts "Opening #{proj}"
  `open #{proj}`
else
  puts "No xcworkspace|xcproj file found"
end

The key to this script is that I don’t get bogged down with details of how to implement it perfectly. It does exactly what I need and should be easy to follow at a later date if I need to change anything.

##Further notes

The initial version of this script had a potential floor which was pointed out by my colleague Oliver Atkinson. In the first instance I didn’t use shellwords to escape the project name. This causes an issue if the name has a space in it, which had never affected me personally as I always camel case my project names, but it’s an edge case that will be hit often when sharing code with others.

The main take away from this learning is that I didn’t need to spend hours making the script perfect (and I’m sure it still isn’t) as it suited my requirements - as soon as the requirements change it’s time to fix it up and make it work.