7

如何获得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];
}
4

3 回答 3

8

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

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

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

请注意,您不应将此方法用于日志记录/调试以外的目的。也就是说,您不应该依赖在框架版本之间具有特定格式的框架类的描述,而是开始做一些事情,比如根据另一个描述字符串构造对象。

于 2012-08-20T17:21:22.317 回答
3

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

一些 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
于 2012-08-20T17:19:35.170 回答
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;
}
于 2012-08-20T17:49:26.757 回答