문제

나는 여기서 요점을 놓치고 혼란스러워하고 있다고 확신합니다. 인스턴스 변수의 값을 콘솔에 인쇄 할 객체에 대한 간단한 설명을 어떻게 작성할 수 있는지 말해 줄 수 있습니까?

또한 : 어쨌든 정보를 블록으로 제시 할 수 있습니까 (즉, 10 IVAR가 10 명을 가지고 있다면 모두 하나씩 돌아 오는 데 고통이 될 것입니다).

@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 : Syntax와 같은 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