我非常确定我只是错过了这里的要点,并对此感到困惑。谁能告诉我,我如何为一个对象写一个简单的描述,以便将其实例变量的值打印到控制台。
还有:有没有办法以块的形式呈现信息(例如,如果你有10个iVars,让它们一个接一个地返回将是一件很痛苦的事情)
@interface CelestialBody : NSObject {
NSString *bodyName;
int bodyMass;
}
- (NSString *)description {
return (@"Name: %@ Mass: %d", bodyName, bodyMass);
}干杯-加里-
发布于 2009-09-17 19:55:42
- (NSString*)description
{
return [NSString stringWithFormat:@"Name: %@\nMass: %d\nFoo: %@",
bodyName, bodyMass, foo];
}发布于 2009-09-17 19:59:24
看看this question的答案。代码重现如下:
unsigned int varCount;
Ivar *vars = class_copyIvarList([MyClass class], &varCount);
for (int i = 0; i < varCount; i++) {
Ivar var = vars[i];
const char* name = ivar_getName(var);
const char* typeEncoding = ivar_getTypeEncoding(var);
// do what you wish with the name and type here
}
free(vars);发布于 2009-09-17 21:19:44
正如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上的类别,否则可能会导致无限的递归。
https://stackoverflow.com/questions/1440974
复制相似问题