Mistakes Were Made: Description Isn’t Enough

It’s my turn to take a crack at a “Mistakes Were Made” post, and this one happens to be about my first post on this blog. If you didn’t happen to catch that one – it was a post about improving your debugging process by giving your objects (More) Descriptive Logging. As it turns out, the post wasn’t 100% accurate.

I basically said, in a nutshell, that overriding the description method would allow you to have a custom object description that would be used when the object was added to a formatted string with %@ (like you use in NSLog), or when using the po command in GDB. It turns out, that last bit is where the inaccuracy lies.

Recently at our day job, Joel was trying to get some information about a slew of custom objects that were tucked off in an array. He was getting tired of all the casting and property-to-method converting that was necessary to get the relevant info through GDB; and then he remembered my blog post, and implemented a slick description method that would provide him all the bits he cared about in one single po command. Except, it didn’t work. In this case, Joel’s objects were subclasses of CALayer, and rather than his informative string, all he saw was the standard CALayer output.

<SomeLayer:0x915a8b0; position = CGPoint (0 0); bounds = CGRect (0 0; 100 100); >

We were perplexed; and Joel questioned whether or not I had even tested any of this before making a blog post about it (what a jerk). Some grumbling and searching later, we came up with this document, Technical Note TN2124 (otherwise known as “Mac OS X Debugging Magic”, it is a worthwhile bookmark, as it’s got gobs of good information for debugging objective-c). The Cocoa and Cocoa Touch section starts out discussing the same description methods we talked about before, but also contains an interesting note (emphasis added by me).

Note: print-object actually calls the debugDescription method of the specified object. NSObject implements this method by calling through to the description method. Thus, by default, an object’s debug description is the same as its description. However, you can override debugDescription if you want to decouple these; many Cocoa objects do this

There it is folks, po doesn’t actually call description, it calls debugDescription. My original tests worked because NSObject doesn’t do anything special with debugDescription and simply calls off to description. If you want to implement a custom description method, to keep some superclass from hijacking it, I’d suggest always just doing the following:

- (NSString *)description
{
	return @"my awesome description";
}

- (NSString *)debugDescription
{
	return [self description];
}
Jerry Jones

About Jerry Jones

Co-Founder of Spaceman Labs, Inc. Formerly of Mellmo, Inc. iOS Developer since 2007. You can find me on LinkedIn, Twitter, and doing backflips on jet skis.
This entry was posted in Code and tagged , , , . Bookmark the permalink.