override description or stringValue in cocoa?
I want to have an descriptive string for an object in Cocoa. I'm thinking about overr开发者_如何学编程iding 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?
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:@"%@ <%p>", NSStringFromClass([self class]), self];
}
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.
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.
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.
精彩评论