在Objective-C中获取id的字符串表示形式

时间:2012-08-20 17:10:00

标签: iphone objective-c ios macos nsstring

如何获得id对象的最佳字符串表示形式?

以下是否正确?有更简单的方法吗?

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

3 个答案:

答案 0 :(得分:8)

description方法是NSObject protocol的一部分,因此Cocoa中的任何对象都会响应它;你可以这样发送description

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

此外,NSLog()会将description发送给作为参数传递给%@说明符的任何对象。

请注意,除了记录/调试之外,不应将此方法用于其他目的。也就是说,您不应该依赖于框架版本之间具有特定格式的框架类的描述,而是开始基于另一个描述字符串构造对象。

答案 1 :(得分:3)

由于所有对象都继承自NSObject,因此它们都响应描述方法。只需在类中重写此方法即可获得所需的结果。

某些Cocoa类(如NSNumber)中的描述方法在内部调用stringValue方法。例如......

NSNumber *num = [NSNumber numberWithFloat:0.2f];
NSString *description1 = num.stringValue;
NSString *description2 = [num description];

NSLog("%@", description1);
NSLog("%@", description2);

...具有相同的输出:

Printing description of description1:
0.2
Printing description of description2:
0.2

答案 2 :(得分:0)

我喜欢我看起来很好看:有时候Xcode剥掉换行符其他时间没有,所以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;
}