How do you get the best string representation of an id object?
Is the following correct? Is there a simpler way?
id value;
NSString* valueString = nil;
if ([value isKindOfClass:[NSString class]]) {
valueString = value;
} else if ([value respondsToSelector:@selector(stringValue)]) {
valueString = [value stringValue];
} else if ([value respondsToSelector:@selector(description)]) {
valueString = [value description];
}
The
descriptionmethod is part of theNSObjectprotocol, so any object in Cocoa will respond to it; you can thus just senddescription:Also,
NSLog()will senddescriptionto any object passed as an argument to the%@specifier.Note that you should not use this method for purposes other than logging/debugging. That is, you should not rely on the description of a framework class having a particular format between versions of the framework and start doing things like constructing objects based on another’s description string.