Category Archives: Coding standards

Coding Standards: Improve your standards and productivity with XCode code snippets

I’m not really sure why this feature isn’t as well known as it ought to be – XCode allows you to create custom code snippets for using within your workspace. What’s even more awesome here is that you can share them with your fellow developers and in this way improve your organisational coding standards. Here’s how it’s (easily) done:

Create your snippets

Step 1: Make sure you’re looking at the utilities view on the right. If it’s out of sight, make sure the rightmost button of these three is selected:

Screen Shot 2013-01-04 at 4.04.41 PM

Step 2: Select the curly bracket icon (“Code Snippets Library”) on the bottom pane of the utilities view:

Screen Shot 2013-01-04 at 4.05.39 PM

Step 3: You should now see the existing snippets in the library: these are included by default and contain some useful C, C++, Objective-C and other standard snippets for your coding pleasure. But we’re here to learn how to add some of our own, aren’t we?

Step 4: Write some perfect code. This is code you are proud of, even if it’s one or two lines. Code that you could see in someone else’s project one day and be proud to call your own. Whatever code you’re using, don’t forget that you’re writing a code template so don’t give too much thought to instance names and other interchangeable elements.

Step 5: Select and drag your code from the main view and into the code snippet library

Step 6: You should now see a new “User” code snippet in the library labeled “My Code Snippet”. Well, obviously it’s not my code snippet but who knows what they were going for here…

Screen Shot 2013-01-04 at 4.10.21 PM

Step 7: Edit your snippets attributes – to do this you need to click the “edit” button on the bottom left of the popup. You’ll then get the chance to change the following:

  • Title – this is what you’ll see in your workspace instead of “My Code Snippet”.
  • Summary – for your own pedantic needs.
  • Platform – iOS or OS X.
  • Language – the programming language the snippet is written in.
  • Completion Shortcut – This one’s important – this is the few letters of code you’ll write until auto-complete understands that you want to use this snippet in your code. It’s extremely useful and I strongly recommend you use something distinct here that you’ll always remember to use.
  • Completion Scopes – These are the scopes in which you wish for auto-complete to recognise your completion shortcut. Note that the options vary depending on the programming language you’ve chosen.
  • Body – This is where the magic happens. It should already contain your pre-written code only now is the time to define the easy-to-access quick edit fields. In step 8, I’ll elaborate a bit more on this.

Screen Shot 2013-01-04 at 4.13.06 PM

Step 8: Create a perfect template – think of the context in which you’re bound to use this code snippet. For instance, a code snippet for defining a UISegmentedControl appearance will contain hard-coded [UISegmentedControl appearance] calls and UIFont instantiating code, whereas something more general such as a singleton design pattern definition will need to be more flexible – you will want to give your future-self the opportunity for fast access to the class name as well as instance names in this scenario. In order to define text as a field designed for quick-access, just wrap it with <# and #> signs, like so:

Screen Shot 2013-01-04 at 4.24.54 PM

so that this snippet, when used, will create the following code:

Screen Shot 2013-01-04 at 4.26.03 PM

Keep in mind that you can quick-access both the “property” and “propertyIvar” fields using TAB, just like any autocomplete suggestion you get by default.

Don’t be a snippet-hog. Share!

Apparently, this is a snippet-hog

Apparently, this is a snippet-hog

You can access all your custom snippets via ~/Library/Developer/Xcode/UserData

You’ll see a file for each snippet you’ve written but unfortunately you won’t be able to make sense of them by the filename alone (You could try opening them in a text editor and viewing their contents to understand which is which).

Send your collaborators these snippets so there is standardized code you agree on. This is a huge advantage when working with other developers and can be a great tool for making sure people are writing code properly.

That’s it!

I hope you enjoy fiddling around with this, it gave me the chance to write code way faster and standardize practices with my co-developers.

Advertisements

Coding Standards: Fast enumeration is not the only way

Lately I’ve been experimenting more and more with blocks in Objective-C: I started writing much more block-oriented code, integrated blocks into existing classes that I’ve written and I generally find myself thinking about how to make code more efficient, readable and bug-free using blocks.

As part of this blocky transformation that I’m going through, I have discovered some very convenient ways to enumerate collections (namely NSSet, NSArray and NSDictionary). These classes have built-in instance methods that allow you to traverse their contents in a very convenient, block-based way.

Examples please…?

Here are a couple of good examples for using block based enumeration:

NSArray

    NSArray *myBeers = @[@"Hoegaarden",@"Leffe",@"Guiness",@"Corona"];
    [myBeers enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        NSString *beerName = obj;
        NSLog(@"Beer #%d is %@",idx,beerName);
        if ([beerName isEqualToString:@"Guiness"]) {
            //Assigning YES to the stop variable is the equivalent of calling "break" during fast enumeration
            *stop = YES;
        }
    }];

NSDictionary

    NSDictionary *countriesToBeers = @{@"Belgium" : @"Duvel",
                                       @"Ireland" : @"Guiness",
                                       @"Mexico" : @"Dos Equis"};
    [countriesToBeers enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
        NSString *country = key;
        NSString *beer = obj;
        NSLog(@"The best beer in %@ is %@. No doubt.",country,beer);
    }];
But why blocks??

But why blocks?? I love fast enumeration!

Well… I’m not saying that fast enumeration is always bad, but block enumeration has it’s advantages:
1. It’s a bit faster. And I say “a bit” because I’m demonstrating this principal using very simple examples. Once enumeration is done on  more complex structures, the elimination of the need for using NSFastEnumeration’s overhead results in a more significant speedup.
2. It gives you a bonus. For NSArrays, you gain a free index variable you can use, no extra charge. For NSDictionaries you get a reference for the object’s key, as well as the object itself without any need for extra code. This means that you can traverse a dictionary’s overall contents and not only it’s values or keys separately.

Hope this has opened your mind to better coding standards. Let the weekend begin!

Coding standards: New Objective-C syntax that will make your code beautiful

Around the time that iOS 6.0 was introduced, Apple also submitted some “literal syntax” improvements to the LLVM project. These improvements include easy-to-read-and-write code improvements that are, in my opinion, worth getting used to.

Here are some examples of what I’m talking about:

NSArray

Up until now, every time you wanted to create an array with predefined objects, you’d have to define it as something similar to:

NSArray *foodArr = [NSArray arrayWithObjects:@"hamburger",@"steak",@"salad"];

But now, thanks to the NSArray literals, you can simply do:

NSArray *foodArr = @[@"hamburger",@"steak",@"salad"];

NSDictionary

Using literals with NSDictionary makes the awful:

NSDictionary *petsDict = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"fido",@"rex",@"simba", nil] forKeys:[NSArray arrayWithObjects:@"dog",@"dino",@"lion", nil]];

available with a simple and understandable:

NSDictionary *petsDict =
@{  @"dog":@"fido",
    @"dino":@"rex",
    @"lion":@"simba" };

NSNumber

NSNumber literals make it easy to instantly create NSNumber instances with various primitive data types such as:

NSNumber *theIntFive = @5
NSNumber *aBooleanYes = @YES
NSNumber *floatPi = @3.14f

Aren’t these nicer than the [NSNumber numberWith…] convention?

 

I think that once these literal standards become something you’re accustomed to, your code will look better and your collaborators will become less eager to hunt you down and hit you with heavy office supplies for writing unreadable code. Enjoy!