正如 Jason 所写,您应该使用 stringWithFormat: 来使用类似 printf 的语法来格式化字符串。
-(NSString*)description;
{
return [NSString stringWithFormat:@"Name: %@ Mass: %d", bodyName, bodyMass];
}
为避免为许多类一遍又一遍地编写此代码,您可以在 NSObject 上添加一个类别,以便您轻松检查实例变量。这将是糟糕的性能,但适用于调试目的。
@implementation NSObject (IvarDictionary)
-(NSDictionary*)dictionaryWithIvars;
{
NSMutableDictionary* dict = [NSMutableDictionary dictionary];
unsigned int ivarCount;
Ivar* ivars = class_copyIvarList([self class], &ivarCount);
for (int i = 0; i < ivarCount; i++) {
NSString* name = [NSString stringWithCString:ivar_getName(ivars[i])
encoding:NSASCIIStringEncoding];
id value = [self valueForKey:name];
if (value == nil) {
value = [NSNull null];
}
[dict setObject:value forKey:name];
}
free(vars);
return [[dict copy] autorelease];
}
@end
有了这个,实现描述也是小菜一碟:
-(NSString*)description;
{
return [[self dictionaryWithIvars] description];
}
不要将此description
作为 NSObject 上的类别添加,否则您可能会以无限递归告终。