Get id string representation in Objective-C

How to get the best string representation of an id object?

Is the following correct? Is there an easier 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]; } 
+7
source share
3 answers

The description method is part of the NSObject protocol, so any object in Cocoa will respond to it; you can just send description :

 for( id obj in heterogeneousCollection ){ [obj description]; } 

In addition, NSLog() will send a description any object passed as an argument to the %@ specifier.

Please note that you should not use this method for purposes other than logging / debugging. That is, you should not rely on the description of the infrastructure class, which has a specific format between the versions of the framework, and start doing things like creating objects based on another description line.

+8
source

Since all objects inherit from NSObject, they all respond to the description method. Just override this method in your classes to get the desired result.

The description method in some Cocoa classes, such as NSNumber, calls the stringValue method internally. For example...

 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 
+3
source

I like mine to look beautiful: sometimes Xcode does not wrap a new line in other cases, so YMMV:

 - (NSString *)description // also used for comparison purposes { NSMutableString *str = [NSMutableString stringWithCapacity:256]; #ifndef NDEBUG // so in Distribution build, this does not get included [str appendFormat:@"Address ID=\"%@\"\n", [self.privateDict objectForKey:kID]]; [str appendFormat:@" usrID: %@\n", [self.privateDict objectForKey:kADuserID]]; [str appendFormat:@" first: %@\n", [self.privateDict objectForKey:kADfirstName]]; [str appendFormat:@" last: %@\n", [self.privateDict objectForKey:kADlastName]]; [str appendFormat:@" address: %@\n", [self.privateDict objectForKey:kADaddress]]; [str appendFormat:@" suite: %@\n", [self.privateDict objectForKey:kADsuiteApt]]; [str appendFormat:@" city: %@\n", [self.privateDict objectForKey:kADcity]]; [str appendFormat:@" state: %@\n", [self.privateDict objectForKey:kADstate]]; [str appendFormat:@" zip: %@\n", [self.privateDict objectForKey:kADzipCode]]; [str appendFormat:@" phone: %@\n", [self.privateDict objectForKey:kADphone]]; #endif return str; } 
0
source

All Articles