Alex Rivera | Logout

Get string representation of id in Objective-C

Asked 2012-08-20T17:10:00.290
8

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];
}
Edit
Report

1 Answer

8

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.

answered 2012-08-20T17:21:22.317

Your Answer