5 Time-saving Objective-C tips every developer should know

Batman Flat White Coffee

Here’s a quick fire list of 5 time-saving Objective-C tips that every developer should know. Perfect for making time for that extra coffee!

1. Enum shorthand

Enums at their simplest are labelled sets of integers. Where an inexperienced programmer might use a number to represent the download state of an image lets say, e.g. 0 = queued, 1 = downloading, 2 = downloaded, 3 = complete… When using these numbers in actual code a simple slip of the finger on the keyboard and they could easily type an extra digit in their if statement or assignment. These types of errors don’t usually show up when compiling. Even worse, these are usually obscure errors that only reveal themselves at run-time and only then when things don’t work as expected often requiring considerable debugging effort.

This is where enums step in. Enums are really handy and allow you to associate symbols or ‘labels’ with integers. If you type an enum value that doesn’t exist the compiler steps in and reports an error at compile-time instead and Xcode will probably suggest a fix for you if it was a typo! The other benefit of enums is that you can quickly add new values into them and assuming your code doesn’t save the integer to disk your code will automatically work with the new values.

There are a couple of different ways to define enums but the easiest way which will also provide Xcode with some extra compiling hints is as follows:

Continue reading

Bluetooth 4.0 LE – The Bluetooth Renaissance

Bluetooth 4.0 LE LogoSometimes a technology comes along that seems like such a good idea you wonder why it was never created in the beginning. For me, Bluetooth was one of those technologies. It’s been around since the late nineties and was incredibly powerful, especially for PDAs and phones but has always been overshadowed by the complimentary WiFi standard and surprisingly inflexible Bluetooth profiles which define the protocol, format and intended use of the data being communicated such as a Modem profile or headset profile.

It’s strength lies in allowing devices to talk to each other over a short distance with low energy and relatively easy setup but while many developers, makers and designers hoped to make use of it as a “wireless USB cable”, the reality was that most uses didn’t fit within the defined “profiles” and so developers opted for the Serial Profile – a generic profile that shuffles bits to virtual serial ports. Serial ports are decades old and because there is no context of what the data is inside the Serial port it’s very easy to bind the wrong program to the wrong device. For example, a data logging program trying to read the serial data from a serial port joystick would probably work or worse still would most likely silently do nothing. This adds confusion and frustration for the user. Compare this experience to using a USB device – you plug it in and open up the program and it recognises the device and starts using it. You don’t see incompatible devices, you can’t connect it to the wrong thing, it just works which is probably why USB is so popular.
Continue reading

Apple WWDC 2012 Session Videos Live

This is a heads up for anyone who does iPad or iPhone development; Apple have made available their awesome WWDC 2012 sessions videos to developers! iOS 6 features such as Passkit, maps and Facebook looks interesting as does the new Game Center functionality such as “Challenges” along with a whole host of new APIs and technologies. More information can be found on the Apple iOS 6 site and the developers’ iOS 6 overview site.

You should also look at the new OS X technologies in the soon-to-be-launched Mountain Lion release. Notification Center seems like such a natural addition that I’m surprised Apple didn’t add it in back in the early days of Mac OS X and Game Center will be exciting to play with on the Mac. I just hope it doesn’t distract me too much from work!

Of course most of it is still under a non-disclosire agreement so only blog and comment about the publicly announced WWDC stuff but this will good to play with over the summer when it’s too hot to be outside.

‘Cut the Rope’ HTML5 JavaScript Preloader

Screenshot of Cut the Rope HTML5 Javascript web appDevelopers from the popular iPhone game Cut the Rope and a crack team of HTML5 gurus from PixelLab, have developed an awesome JavaScript version that runs inside most modern web browsers using JavaScript and a number of powerful HTML5 features such as canvas and media APIs. You can find out how they did it from the behind-the-scenes video they’ve posted.

One of the interesting snippets from the dev blog is that the group behind the creation of the app have released an open-source preloader for JavaScript apps called PxLoader. It supports some extremely useful features such as being able to load in your canvas images in groups, use progress bars, get callbacks when various groups have loaded and supports a plug-in architecture so you can load in sounds too. It’s released under a fairly liberal MIT license and the PxLoader source is available on GitHub.

Image loading in Groups

A good example is using it in an HTML5 game to load menu sprites before actual game sprites since you would want the menu to display and load first. PxLoader can also provide progress updates to many listeners and will scope the updates and statistics to only the set of “tags” a listener is interested in, a tag being the text name of that group.

// Delay each image and append the timestamp to prevent caching 
var baseUrl = 'http://thinkpixellab.com/pxloader/slowImage.php?delay=1time=' + new Date, 
    $log = $('#sample3-log').val(''), 
    $menuProgress = $('#sample3-menuProgress').text('0 / 50'), 
    $gameProgress = $('#sample3-gameProgress').text('0 / 50'), 
    $totalProgress = $('#sample3-totalProgress').text('0 / 100'), 
    loader = new PxLoader(); 

// Queue 50 images for each section 
var addImagesForTag = function(tag, $progress) { 
    for(var i=0; i < 50; i++) { 
        var imageUrl = baseUrl + '&i=' + i + '&tag=' + tag; 
            pxImage = new PxLoaderImage(imageUrl, tag); 
        pxImage.imageNumber = i + 1; 
        loader.add(pxImage); 
    } 

    // add a listener to update progress for the tag 
    loader.addProgressListener(function(e) { 
        $progress.text(e.completedCount + ' / ' + e.totalCount); 
    }, tag); // scope listener to the current tag only 
}; 

addImagesForTag('menu', $menuProgress); 
addImagesForTag('game', $gameProgress); 

// Listen to every event to update total progress 
loader.addProgressListener(function(e) { 

    // log which image completed 
    var line = ' Image ' + e.resource.imageNumber + 
        ' Loaded [' + e.resource.tags[0] + ']\r'; 
    $log.val($log.val() + line); 

    // scroll to the bottom of the log 
    $log.scrollTop($log[0].scrollHeight); 

    // the event provides stats on the number of completed items 
    $totalProgress.text(e.completedCount + ' / ' + e.totalCount); 
}); 

// Start downloading images for tags in prioritized order 
loader.start(['menu', 'game'])

You can play with a working example of the group image loading on the PxLoader homepage (Sample 3).

How to call a block after a delay

On iOS and on OS X you sometimes need the User Interface to update after a short delay. The old way of doing it was calling the performSelector:withObject:afterDelay: selector on any NSObject subclass but that requires defining a new method in your class and you can only pass one object as a parameter.

Instead, you can use dispatch_after from the Grand Central Dispatch APIs to execute code within a block after a certain time interval. Don’t be afraid, it might be low-level C but you can cut and paste and just put your code inside and it will retain the variable scope that blocks usually do!

double delayInSeconds = 0.5;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){

  // Your code here

});