Category Archives: Quick tips

Quick Tip: Peeking into objects

Hi everyone!

Remember this post from way back about creating custom LLDB summaries for your objects so that you can conveniently inspect objects while debugging? Well the folks at Cupertino have been hard at work and have shipped an awesome feature with the new XCode 5.1 – “Debug Quick Look” which renders my previous post pretty much useless (and I mean useless in the sense that it is now a magnitude easier to accomplish something even better).

So basically this is how it works- You can now provide a visual “meaning” to objects you instantiate by implementing the following method:

- (id)debugQuickLookObject{
    //TODO: Return anything you want to see while debugging
}

Let’s take a look at the following example – I’ve created a data type that maps an NSString to a UIColor (don’t ask me why). It’s really easy to think of how you’d like this visualized for debugging purposes, so rather than seeing something like this:

{
   Coffee = "UIDeviceRGBColorSpace 0.6 0.4 0.2 1";
   Deep = "UIDeviceRGBColorSpace 0.5 0 0.5 1";
   Ocean = "UIDeviceRGBColorSpace 0 0 1 1";
   Tree = "UIDeviceRGBColorSpace 0 1 0 1";
}

…we can now use the debugQuickLookObject and see something like this:
Screen Shot 2014-02-08 at 6.50.37 PM
Here’s the code that is responsible for generating this wonder:

- (id)debugQuickLookObject
{
    NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] init];
    [self.theDict enumerateKeysAndObjectsUsingBlock:^(NSString *str, UIColor *color, BOOL *stop) {
        NSAttributedString *colorAttrStr = [[NSAttributedString alloc] initWithString:[str stringByAppendingString:@"\n"] attributes:@{NSForegroundColorAttributeName : color}];
        [attrStr appendAttributedString:colorAttrStr];
    }];
    return attrStr;
}

Now remember, this is code that actually runs while your process is paused so you want to:

  1. Run as little code as possible (creating a caching mechanism is recommended)
  2. Avoid changing your application’s internal state – anything that runs in the debugQuickLookObject method actually interacts with your application’s classes, instances and general state so don’t mess with anything (think of this as Marty avoiding his parents in Back to the Future).

The cool thing about this feature is that you can basically return anything that has visual representation (Strings, Attributed strings, images, bezier paths, views, urls, etc…) and see them while debugging. To access the provided quick look object, all you need to do is hover over the instance and click the little eye icon.

I can already think of dozens of places in my code where everyone collaborating with me could benefit from this visualization (including myself). Also, it would be nice to see this becoming a community thing – Developers writing open source projects could enrich documentation using custom quick looks and generally anyone could write quick looks for existing complex and hard-to-debug code.

The Capper

I’ve recently written a little handy utility that some might find useful. The main idea: helping programers and designers understand the idea of resizable images and calculate the correct cap insets for an image based on how you want it to look.

This is a stretched image without defining cap insets. Ewwww.

This is a stretched image without defining cap insets. Ewwww.

After playing around with the controls - viola! Also, you'll find all the code you need at the bottom.

After playing around with the controls – viola! Also, you’ll find all the code you need at the bottom.

Using this tool is pretty easy – download the XCode project from gitHub or CocoaControls, add the image you want to fiddle around with into the project and update the image’s name in Configuration.h

I know the name I chose kinda sounds like “The Crapper”. I only noticed it a moment before pushing to git. Screw you.

Enjoy!

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!

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 🙂

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.

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 🙂