我很确定我只是在这里忽略了这一点而感到困惑。任何人都可以告诉我如何为一个对象编写一个简单的描述,该对象将打印出实例变量的值到控制台。

另外:无论如何都要把这些信息作为一个块来呈现(例如,如果你有10个iVars,那么让它们全部逐个返回会很痛苦)

@interface CelestialBody : NSObject {
    NSString *bodyName;
    int bodyMass;
}

- (NSString *)description { 
    return (@"Name: %@ Mass: %d", bodyName, bodyMass);
}

欢呼 - 加里 -

有帮助吗?

解决方案

- (NSString*)description
{
  return [NSString stringWithFormat:@"Name: %@\nMass: %d\nFoo: %@",
     bodyName, bodyMass, foo];
}

其他提示

查看这个问题。代码转载如下:

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);

正如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上的类别,否则最终可能会无限递归。

你在那里所拥有的并不是一个坏主意,它几乎可以实现。

// choose a short name for the macro
#define _f(x,...) [NSString stringWithFormat:x,__VA_ARGS__]

...

- (NSString *) description
{
    return _f(@"Name: %@ Mass: %d", bodyName, bodyMass);
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top