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 description
method is part of the NSObject
protocol, so any object in Cocoa will respond to it; you can thus just send description
:
for( id obj in heterogeneousCollection ){
[obj description];
}
Also, NSLog()
will send description
to 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.
Since all objects inherit from NSObject, they all respond to the description method. Simply override this method in your classes to get your desired result.
The description method in some Cocoa classes like NSNumber call the stringValue method internally. For instance...
NSNumber *num = [NSNumber numberWithFloat:0.2f];
NSString *description1 = num.stringValue;
NSString *description2 = [num description];
NSLog("%@", description1);
NSLog("%@", description2);
...have the same output:
Printing description of description1:
0.2
Printing description of description2:
0.2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With