Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get string representation of id in Objective-C

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];
}
like image 978
hpique Avatar asked Aug 20 '12 17:08

hpique


2 Answers

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.

like image 98
jscs Avatar answered Nov 04 '22 04:11

jscs


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
like image 42
Pedro Mancheno Avatar answered Nov 04 '22 03:11

Pedro Mancheno