繁体   English   中英

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

[英]Get string representation of id in Objective-C

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

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

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

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

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

由于所有对象都继承自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

我喜欢我看起来很好看:有时候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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM