tags:

views:

210

answers:

4

I want to have an descriptive string for an object in Cocoa. I'm thinking about overriding either the description method or the stringValue method. Which is preferable and why? The only guideline I could find was in here stating

You are discouraged from overriding description.

Is this indeed what you would suggest? Any other preferred overrride point?

+4  A: 

I personally override description in virtually all subclasses I create. I guess, like Tom Duckering writes in his comment, that your quote only applies to Managed Objects.

- (NSString *) description
{
    return [NSString stringWithFormat:@"%@ <0x%x> (more stuff, depending on subclass)", NSStringFromClass([self class]), self, ...];
}
Pascal
+2  A: 

description is the way to go, that's what it's called to supply string representation of an object.

- (NSString*)description
{
    return [NSString stringWithFormat:@"%@, %@; %@", a, b, c];
}

I believe suggested by Hillegass' book as well.

stefanB
thanks, for the Hillegass reminder as well ;)
mvexel
A: 

You can also override [NSObject debugDescription] which is called by the debugger. It's what is called when use "print to console" in the debugger. You can also call it directly in a NSLog.

By default in most classes debugDescription just calls description but you can make them return separate strings. It's a good place to load up the output with details.

Categories are a good place to park the method for both your custom classes and existing classes. This is especially useful because you can include the category in a debug build but exclude it in the release. If the category is not present, the code calls the default class method instead.

I have a debugging category for UIView that dumps out every attribute I could think of. If I hit a nasty bug I just include the category and then I can see everything about every view right in the debugger console.

TechZen
+2  A: 

To answer your question from the other direction, stringValue is something altogether different—it doesn't describe the receiver, it's a property of it. Your custom description may even include the stringValue, or an excerpt of it if it's long.

A key difference is that stringValue is often a mutable property (see, for example, that of NSControl), whereas description is always an immutable property, computed upon demand.

Peter Hosey