Quick Tip: UIAlertView with block callbacks

What bothers me

Now more than ever I find myself pondering over the question: “Why delegates? Why???”

Last time I found myself asking this was when I had to display some UIAlertViews in a project (though I really tend to stay away from them for UX reasons).

If you’ve had a little more than 10 days of experience in iOS development, you’ve probably already used these for either feedback to the user or as a way to get input from the user. Using it is pretty simple – you create an instance of the UIAlertView while assigning it a title, a message and titles for it’s button(s) and a delegate. Next, you call “show” and viola, it pops out:

Screen Shot 2013-01-31 at 11.30.17 PM

The problem starts when you want to handle the user’s action – if we’re only talking about a 1-button “OK” alert then this is a non-issue, but if there are multiple buttons here and you wish to handle the user’s action according to their choice – that’s where the spaghetti code is born.

Spaghettelegate (It is too a word!)

Now you’ll find yourself implementing yet another delegate method for when the user dismisses the alert. Won’t it go along nicely with all the other out-of-order methods and code in your class? Something like:

- (IBAction)okPressed:(id)sender {
    UIAlertView *nagAlert = [[UIAlertView alloc] initWithTitle:@"Are you sure" message:@"No, seriously are you sure??" delegate:self cancelButtonTitle:@"Not really" otherButtonTitles:@"Yes!", nil];
    [nagAlert show];
}

#pragma mark - SomeDelegate
...

#pragma mark - SomeOtherDelegate
...

#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    switch (buttonIndex) {
        case 0:
            [self quitInRage];
            break;
        case 1:
            [self doSomethingNice];
            break;
        case 2:
            [self breakEverything];
            break;
        default:
            break;
    }
}

And what if you need to display more than one UIAlertView? Do you start tagging each instance when you create it and then check the tag when the delegate method is invoked? Pfff… please…

An elegant approach

The way I decided to get rid of this pattern (once and for all) is to create a block-friendly “UIBAlertView” class (B stands for Block or Brilliant or any other B-related word of your choice). So now creating, displaying and handling an alert is an all-in-one deal like so:

- (IBAction)activateAlert:(id)sender {
    UIBAlertView *alert = [[UIBAlertView alloc] initWithTitle:@"Yes, like this" message:@"What are you looking at?" cancelButtonTitle:@"Leave me alone" otherButtonTitles:@"Button 1",@"Button 2",nil];
    [alert showWithDismissHandler:^(NSInteger selectedIndex, BOOL didCancel) {
        if (didCancel) {
            NSLog(@"User cancelled");
            return;
        }
        switch (selectedIndex) {
            case 1:
                NSLog(@"1 selected");
                break;
            case 2:
                NSLog(@"2 selected");
                break;
            default:
                break;
        }
    }];
}

This is elegant because:
A. When an alert is dismissed, you know exactly which one it is.
B. You’re creating, activating and handling the dismissing of your alert in the same section of code.

The code is available on gitHub and featured in CocoaControls check it out.

Any comments, suggestions or different approaches will be hunted down and executed. Just kidding, suggest away 🙂

Advertisements

UX: There’s a control for that

During my first year at university, I remember my Java professor telling us something I’ll never forget and that still guides me to this day: “Someone already wrote it”. His philosophy was very strong on this – if you’re trying to tackle a general problem, there’s a very good chance that someone already did most of the work and there is probably an open source library that does what you need. That’s the beauty of object oriented programming: If you do things right, everything is modular, plug & play, reusable and it’s especially true when coding for iOS.

There are extremely talented people writing amazing open source code for iOS. You can interact with them on Stack Overflow, where they volunteer their time and experience to help us solve our problems. You can see things they’ve done by browsing GitHub repositories and you can find endless reusable and open source code via simple Google searches.

And there’s even a greater advantage here when discussing user experience. There are hundreds of controls out there, some are free to use under several restrictions and some are for sale, that (if used correctly) give you the chance to create some very creative user interfaces. If you haven’t already, I suggest you give them a try.

A great site for browsing these controls (my personal favorite) is cocoacontrols.com – you can browse iOS and Mac OS X controls by rating, recency or just by keywords. Some very good and popular controls there include:

MFSideMenu – as seen on Path, Facebook and many MANY more:

full-2

MFSideMenu

MBProgressHUD – Great class for displaying blocking activity indicators. You’ve probably run into these in a billion apps:

MBProgressHUD

MBProgressHUD

iCarousel – A very flexible, well written control for beautiful 3D browsing:

iCarousel

iCarousel

I strongly recommend you to browse some or all of the iOS controls that are available for purchase/download. Even if you don’t choose to reuse them (some may not be up to standard, I admit), they will definitely open your mind in terms of what you can do on iOS. Enjoy!

Advanced Issues: Creating custom LLDB object summaries

Update: It’s recommended to read this post before diving in.

Today we’re going to talk about an advanced XCode debugging feature that might improve your bug-extermination practices and efficiency. It’s well known that XCode has great debugging features, some of which were even discussed here in a previous post. These features are sometimes very straightforward and easy to use, but some of them require a bit of digging.

This is the digging kind.

What I’m going to show you is how to create a python script that will “teach” XCode and the LLDB about your object structures – this way, you will be able to immediately get a custom summary of the object you’re reviewing in the debugger and see what’s important to you while debugging.

For the sake of this tutorial, We’ll use a wonderful and widely-popular class called “Beer”. Let’s say that a “Beer” has a name, a price and a rating:

Screen Shot 2013-01-06 at 8.28.13 PM

The problem is that when we use the XCode debugger to inspect a beer object instance, we will automatically be able to see only the pointer address of the instance. This is unlike an NSArray object or an NSString object for instance – in these cases we’ll see the amount of objects in the array or the string itself, respectively. So who the hell cares about the beer’s pointer?? Let’s make this right.

The debugger watchlist - notice the unfair treatment NSArray is getting over Beer. That's just wrong.

The debugger watchlist – notice the unfair treatment NSArray is getting over Beer. Not cool.

So, let’s get started with the Python script that will eventually enable us to see a better summary:

Step 1: Create the Python script.

Create a new “CustomSummaries.py” file and base it on the following code:

Screen Shot 2013-01-06 at 9.13.37 PM

I added this as a screenshot on purpose so that you’ll have to do some work. Lazy bastards.

Here’s what you need to know:

Line 1 – imports the lldb library. Must be in your script in order to work.

Lines 7-8 – This function gets called by default and attaches your custom object summary function to the “Beer” object. Make sure you don’t misspell anything here and that you include all the flags as written above. Replace any “Beer” instance with your own class name.

Line 3-5: This is the definition of the object summary – we extract only the beer’s name and return a string that includes a “name: ” prefix followed by the beer name itself. Note that on line 4 we extract the _name property as defined in the “Beer” class.

The result:

Screen Shot 2013-01-06 at 9.18.41 PM

You can now see the beer name, inline like it were a string object. There’s no need to open the object hierarchy to inspect the beer, it’s right there in front of you.

Step 2: Automate the import

In order for XCode to recognise and run your new script, you’ll have to create a new file in your home folder called “.lldbinit” so that the full path to this file is: ~/.lldbinit

Within this file, add the following line:

command script import PATH_TO_PY_FILE

Make sure you supply the correct, full path to CustomSummaries.py and that’s it, XCode will now include this custom summary every time you run it. If XCode is already running, be sure to restart it in order to see the changes taking place. Enjoy!

Screen Shot 2013-01-06 at 8.31.08 PM

This is how geeks import beer. Geeks, not me.

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.

Quick Tip: Keep your imports nice & tidy

After watching WWDC 2012 session 402 about working efficiently with XCode, I came across a nifty little tweak that may benefit anyone who strives to keep their code clean and tidy. You know how complex classes may sometimes end up with multiple “import” lines and that you can even sometimes loose track of what classes have already been imported? I’m going to show you how to add a new context menu option via Mac OS X’s Automator that does just what you need:

Step 1: Open Automator – It should be fairly easy to find via spotlight or just go the Applications folder and look for a robot that looks like a pissed-off version of Eve from WALL-E

Screen Shot 2012-12-29 at 2.12.13 PM

Step 2: Once you open Automator, you’ll be asked about what type of document you wish to create. Select “Service”.

Screen Shot 2012-12-29 at 12.40.55 PM

Step 3: In the workflow inspector, mark the “Service recieves selected” with “text”. Next, you can decide that you want this new service to be available only in XCode or in any other app you’re running, I just left it with the default “any application”. Be sure to tick the “Output replaces selected text” so that the operation will replace the imports you’ll select in XCode.

Screen Shot 2012-12-29 at 12.45.05 PM

Step 4: In the “Actions” panel on the left, select “Run Shell Script” as shown here:

Screen Shot 2012-12-29 at 12.45.59 PM

Step 5: Fill in “sort | uniq” to the script body, like so:

Screen Shot 2012-12-29 at 12.47.02 PM

Step 6: hit cmd+s to save your automated service and give it a nice pet name, such as “Igor” or the preferable “Sort & Uniq”. This is what you’ll see in the context menu when right-clicking on selected text.

Step 7: Use it: Open XCode, go to any of your complex classes that have way too much imports, select those imports and right click them. You’ll see the new “Sort & Uniq” option appear under “services” – once you select that, you’ll see that your imports are instantly sorted and any duplicates will be thrown out.

Screen Shot 2012-12-29 at 12.52.13 PM

If you have any other handy ideas about how to use automator to improve XCode use, please share with us through the comments section.

And a happy New Year!

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!

Advanced issues: Asynchronous UITableViewCell content loading done right

Problem?

Haven’t you always wondered why your UITableView is loading “almost” perfectly? I mean, sure- you’ve made it clear to the iOS that all non-trivial cell work (such as downloading images from a remote URL or rendering content) is to be computed asynchronously on a background thread. But sometimes this is not enough, mainly for 2 reasons:

1. Once a cell is out of the visible area, the asynchronous operation you called is still doing work. This often results in unnecessary system resource usage or even buggy table behaviour caused by operations not knowing which cell to return to when they’re done.

2 . UITableViewCells are often reused instances. This means that cells being loaded into the view may sometimes contain data that was loaded originally into a completely different cell. This often causes a “Cell switching” behaviour which can just completely piss you off.

Solved!

First of all it’s important to understand that there are many ways to tackle this issue – some are great ideas and some are, well, awful. The method that I’m about to describe here is based on a demo provided by Apple (namely WWDC 2012 session 211), and you know those guys know a thing or two about iOS.

For our example, I’ll use a simple UITableView instance that is meant for displaying your facebook friends’ names and profile pictures. The main idea is that we start loading the profile images when UITableViewDataSource’s tableView:cellForRowAtIndexPath: is called. If the operation succeeds and the cell is still in view then we simply add the image to the cell’s profile image view (on the main thread). If it’s not – we make sure not to perform the “setImage” part.

Before you start, some prep work: Define an NSOperationQueue for running background operations – in this example, we call it the imageLoadingOperationQueue. Also, define an NSMutableDictionary for storing references to specific operations – in this example we will map the facebook unique ids to the operations on the facebookUidToImageDownloadOperations dictionary.

Most of the important stuff is commented in the code so make sure you read the comments to understand what’s going on:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    FacebookFriend *friend = [self.facebookFriends objectAtIndex:indexPath.row];
    FacebookFriendCell *cell = [tableView dequeueReusableCellWithIdentifier:FB_CELL_IDENTIFIER forIndexPath:indexPath];
    cell.lblName.text = friend.name;

    //Create a block operation for loading the image into the profile image view
    NSBlockOperation *loadImageIntoCellOp = [[NSBlockOperation alloc] init];
    //Define weak operation so that operation can be referenced from within the block without creating a retain cycle
    __weak NSBlockOperation *weakOp = loadImageIntoCellOp;
    [loadImageIntoCellOp addExecutionBlock:^(void){
        //Some asynchronous work. Once the image is ready, it will load into view on the main queue
        UIImage *profileImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:friend.imageUrl]]];
        [[NSOperationQueue mainQueue] addOperationWithBlock:^(void) {
            //Check for cancelation before proceeding. We use cellForRowAtIndexPath to make sure we get nil for a non-visible cell
            if (!weakOp.isCancelled) {
                FacebookFriendCell *theCell = (FacebookFriendCell *)[tableView cellForRowAtIndexPath:indexPath];
                [theCell.ivProfile setImage:profileImage];
                [self.facebookUidToImageDownloadOperations removeObjectForKey:friend.uid];
            }
        }];
    }];

    //Save a reference to the operation in an NSMutableDictionary so that it can be cancelled later on
    if (friend.uid) {
        [self.facebookUidToImageDownloadOperations setObject:loadImageIntoCellOp forKey:friend.uid];
    }

    //Add the operation to the designated background queue
    if (loadImageIntoCellOp) {
        [self.imageLoadingOperationQueue addOperation:loadImageIntoCellOp];
    }

    //Make sure cell doesn't contain any traces of data from reuse -
    //This would be a good place to assign a placeholder image
    cell.ivProfile.image = nil;

    return cell;
}

Now all that’s left to do is to take advantage of a new UITableViewDelegate method introduced in iOS 6.0: It’s called “tableView:didEndDisplayingCell:forRowAtIndexPath:” and It’s called right after the cell we are loading our data into is no longer needed. Sounds like a perfect spot for the following code, which fetches the relevant operation and cancels it:

- (void)tableView:(UITableView *)tableView didEndDisplayingCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    FacebookFriend *friend = [self.facebookFriends objectAtIndex:indexPath.row];
    //Fetch operation that doesn't need executing anymore
    NSBlockOperation *ongoingDownloadOperation = [self.facebookUidToImageDownloadOperations objectForKey:friend.uid];
    if (ongoingDownloadOperation) {
        //Cancel operation and remove from dictionary
        [ongoingDownloadOperation cancel];
        [self.facebookUidToImageDownloadOperations removeObjectForKey:friend.uid];
    }
}

Also, don’t forget to take advantage of the NSOperationQueue and call “cancelAllOperations” when the table is not needed anymore:

- (void)viewDidDisappear:(BOOL)animated {
    [self.imageLoadingOperationQueue cancelAllOperations];
}

That’s it! You now have yourself a UITableView running as smooth as a Ferrari. You’re welcome 😉

Table_Mountain_DanieVDM

Tabelview, Capetown

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!

Quick tip: How to instantly see the error of your XCode ways

I’ve come across a handy little tweak  in XCode that allows you to instantly be aware of the newest error that caused a build failure in your code. The end result is that XCode automatically navigates to whatever line of code is causing the error, which is probably the next thing you would look for anyway. Here’s all you have to do:

QuckTip1

Step 1 Open XCode -> Preferences

Step 2 Navigate to the “Behaviors” tab

Step 3 On the left panel, under “Build”, select the “Fails” section

Step 4 Tick the “Navigate to” checkbox and select “first new issue”

Now next time you build your project and something is wrong, you’ll be taken there immediately to fill in your missing square bracket. Hope this saves you some time 🙂