1

我很确定我只是在这里错过了重点并感到困惑。谁能告诉我如何为一个对象编写一个简单的描述,将其实例变量的值打印到控制台。

另外:是否无论如何将信息呈现为一个块(即,如果您有 10 个 iVar,让它们一个一个返回会很痛苦)

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

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

干杯-加里-

4

4 回答 4

9
- (NSString*)description
{
  return [NSString stringWithFormat:@"Name: %@\nMass: %d\nFoo: %@",
     bodyName, bodyMass, foo];
}
于 2009-09-17T19:55:42.000 回答
5

看看这个问题的答案。代码复制如下:

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-17T19:59:24.440 回答
1

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

于 2009-09-17T21:19:43.937 回答
1

这不是一个坏主意,你在那里拥有什么,它也几乎可以实现。

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

...

- (NSString *) description
{
    return _f(@"Name: %@ Mass: %d", bodyName, bodyMass);
}
于 2009-09-18T04:50:24.153 回答