Blog Archives

The power of concurrency

Hi everyone, and welcome to Saturday night’s advanced session regarding concurrency in iOS.

We all know that some of Apple’s more powerful devices come equipped with multiple cores and we mostly just trust the operating system to utilize this advantage whenever possible, right? Well, turns out there are some cases where we need to explicitly tell the operating system – ‘hey, this code should be executed concurrently’ (iOS is great, but it’s not a magician). Today, we will discuss one of these cases – concurrent enumeration.

Let’s say we have a huge data collection of independent data points and that we wish to execute some heavy mathematical operation on each of them. Now the mathematical operation(s) we wish to apply on a single object is completely orthogonal to all other objects meaning – this is code that’s ideal for running concurrently between processor cores. The way to do this is to enumerate this data collection with the enumerateObjectsWithOptions:usingBlock: method, like so:

[[arr copy] enumerateObjectsWithOptions:NSEnumerationConcurrent usingBlock:^(NSNumber *num, NSUInteger idx, BOOL *stop) {
    //Do some heavy mathematical stuff with 'num'
}];

Just to emphasise the performance gain in using this method rather than fast enumeration, check out the output of running a similar scenario on the iOS simulator (yes, that’s why you see 4 cores):

Using simple, fast enumeration:

Simple

Simple enumeration – takes about 5 seconds to run 10000 iterations. You can see that operations run on one core, while the others are simply kicking back with a beer.

 

Using block enumeration with the NSEnumerationConcurrent option:

Concurrent

Now THAT’S team spirit! About 0.5 seconds to run 1000000 iterations. Unbelievable performance gain.

 

That’s it for today! Hope you find creative, safe ways to use this technique and remember – with great power comes great responsibility, so don’t abuse this API by running things in parallel that shouldn’t.

Quick tip: Bridging the gap between ARC and MRR

Since ARC was introduced, more and more developers have seen the light and joined the hype – it’s less prone to human error, it saves us a lot of code and of course it reduces the headache associated with manual retain-release or ‘MRR’. Of course I believe that a good Objective-C developer needs to be familiar with MRR just as any of us were back in 2011, though I always encourage starting new projects with the “use ARC” checkbox ticked on.

One of my favorite benefits of the way ARC does things is that it won’t let you call methods that aren’t visible / defined in your code. This means that there are naturally many less run-time exceptions of the all time favorite “unrecognized selector sent to instance” kind:

Thanks ARC! How responsible of you to say so…

But things weren’t always this convenient. Objective-C is known to be the relaxed stoner neighbour of programming languages. It lets you pass virtually anything to anything else, doing all the work dynamically at runtime and giving you a false sense of security while you write your code. In the pre ARC era if you weren’t careful enough, your app would have the potential to crash more frequently than an airline in southeast Asia during monsoon season:

Hey man relax, I mean come on… what’s the worst that can happen? Hey are you gonna finish those fries?

So what if we are still stuck on MRR? What if we’re working on an old project or simply want to leave memory management to ourselves? Are we doomed to work with this inconvenient disadvantage? Nope. Just add “-Werror=objc-method-access” to your “warning flags” section in the target build settings and this specific warning will turn into an error. Enjoy!

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.

Pimp your XCode: Add sound to breakpoints

Here’s a neat little trick I’ve come across recently that I find very useful – In XCode, under the “breakpoints” navigator, you can configure an existing breakpoint to play a sound once it is hit. This means that the app doesn’t necessarily have to pause execution so that you know what’s going on. Also, using this in collaboration with some other advanced debugging features may prove to be even more powerful (I recommend WWDC session 412 for some good quality learning).

All you have to do is:

1. Add your breakpoint and open the breakpoint navigator to find it there.

2. Hold alt+cmd while clicking the relevant breakpoint. You’ll see a popup like so:

Screen Shot 2012-12-22 at 11.01.46 PM

3. Press the “Add Action” button – you’ll now see the “Action” section change so that you can select a type of action – pick “Sound”

4. You can either choose a different sound than the default one (maybe a sound of something breaking?) or just leave the default sound as is. It’s also recommended that you tick the “Automatically continue after evaluating” checkbox so that the sound will play without pausing your app.

Screen Shot 2012-12-22 at 11.10.09 PM

And there you have it – breakpoints with sound! I must say I haven’t seen this in any other IDE. Kudos to Apple.

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!