Xcode 5.1's Custom Quick Look Debug Feature

11 March 2014

With Xcode 5, you can Quick Look a whole bunch of different variable types when debugging, like CGPoint, UIImage, NSAttributedString and more. With Xcode 5.1, though, you can now enable Quick Look on your own custom object subclasses.

This means that when debugging, you can provide a visual context of what the object you are inspecting actually is. In the above example, I am seeing a visual representation of my BingoBall object in the form of an attributed string.

Unfortunately, despite being mentioned in the update notes, the feature is well-hidden and whilst not particularly complicated to implement, the process is obscure. Hopefully, this post shines some light on this cool addition.1

In essence, you can think of this feature as a more flexible form of the description method on NSObject. Instead of simply returning a string, you return an arbitrary object by implementing debugQuickLookObject in your subclass.

- (id)debugQuickLookObject {
    // create and return an object that is Quick-Lookable to represent your custom object

    CGSize imageSize = CGSizeMake(150, 150);

    UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0);

    [UIColor.redColor set];
    UIRectFill(CGRectMake(0, 0, imageSize.width, imageSize.height));

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return image;
}

Xcode does not (yet) autocomplete this method so you have to type it manually. Watch your typing — you won’t get warned about misspellings.

You can return any object that Xcode knows natively how to Quick Look. This includes NSString, NSAttributedString, UIImage, CGImageRef, UIBezierPath and even NSURL (it’ll render the document inline).

In the code sample above, I simply render a red square and return it. Obviously, in a real-world scenario, you would want to create an image that reflects the current state of your object. For instance, rather than using UIColor.redColor, you might want to use the value of the color property of your object.

In my use for Bingo Machine, I create an attributed string which offers a lot more context than the object’s description (seen in the console). But I could just as easily generate a rendered image of a bingo ball with the correct number drawn on. Because this method is only called when you Quick Look, the rendering logic can be quite intricate and involved — it doesn’t need to be performant.2 This means you can have both a lightweight description method (for logging arrays and such) and a richer representation in the form of debugQuickLookObject.

1 I first learnt about it from the ‘Hidden Gems’ iOS 7 Tech Talk. You can watch the whole presentation on the Tech Talks pages.

2 This method gets called as part of your application flow, so make sure you aren’t changing state here. You don’t want side-effects to arise from calling this method.