2012-02-29 2 views
0

메인 클래스의 각 서브 클래스에 description 메서드를 오버로드하지만 내부에 필요에 따라 들여 쓰기 속성을 유지하려면 어떻게해야합니까? \ r을 사용하면 새 항목이 들여 쓰기되지 않으므로 도움이되지 않습니다.iPhone - NSArrays 또는 NSDictionaries와 마찬가지로 NSLog 심층 출력 사용자 정의 클래스를 들여 쓰려면 어떻게해야합니까?

- (NSString*) description 
{ 
    NSMutableString* str = [NSMutableString string]; 

    [str appendFormat:@"One attribute : %d\r", self.oneAttribute]; 
    [str appendFormat:@"List : %@\r", self.myArrayOfCustomObjects]; 

    return str; 
} 

- (NSString*) description (on custom object) 
{ 
    NSMutableString* str = [NSMutableString string]; 

    [str appendFormat:@"One attribute : %d\r", self.oneAttribute]; 
    [str appendFormat:@"One other attribute : %d\r", self.oneOtherAttribute]; 

    return str; 
} 

답변

2

편집 : 코멘트에 지적

으로,이 조각을 사용하여 소스 파일의 #include <objc/runtime.h> 라인을 포함해야합니다.


당신은 좋은 서식 객체의 모든 속성을 출력하기 위해이 코드 (나는 그것을 발견 어디 기억하지 않는다)를 사용할 수 있습니다

:

- (NSString*)description { 
    NSMutableString* string = [NSMutableString stringWithString:@""]; 
    unsigned int propertyCount; 
    objc_property_t* properties = class_copyPropertyList([self class], &propertyCount); 

    for(unsigned int i = 0; i < propertyCount; i++) { 
     NSString *selector = [NSString stringWithCString:property_getName(properties[i]) encoding:NSUTF8StringEncoding] ; 

     SEL sel = sel_registerName([selector UTF8String]); 

     const char* attr = property_getAttributes(properties[i]); 
     switch (attr[1]) { 
      case '@': 
       [string appendString:[NSString stringWithFormat:@"%s : %@\n", property_getName(properties[i]), [self performSelector:sel]]]; 
       break; 
      case 'i': 
       [string appendString:[NSString stringWithFormat:@"%s : %i\n", property_getName(properties[i]), [self performSelector:sel]]]; 
       break; 
      case 'f': 
       [string appendString:[NSString stringWithFormat:@"%s : %f\n", property_getName(properties[i]), [self performSelector:sel]]]; 
       break; 
      default: 
       break; 
     } 
    } 
    free(properties); 

    return string; 
} 
+0

어떤 사용자 정의 클래스 객체의 배열에 대한 ? – Oliver

+0

그들에 대해? 배열이 각 사용자 정의 객체를 포맷하지 않거나 배열을 전혀 인쇄 할 수 없다는 말입니까? –

+0

\ n 작동하지 않고 콘솔에 씁니다. – Oliver