Get string representation of id in Objective-C

ios, iphone, macos, nsstring, objective-c

Solution

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.

Problem

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]; } ```

Original source