2012-02-29 19 views
0

我用一個description方法重載我的主類的每個子類,但是在它裏面,我該如何使屬性保持縮進?使用\ r不起作用,因爲新項目沒有縮進。iPhone - 我如何獲得NSLog深度輸出自定義類縮進,因爲它爲NSArrays或NSDictionaries?

- (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 2012-02-29 01:47:17

+0

他們呢?你是說數組不會格式化每個自定義對象,或者根本不能打印數組? – 2012-02-29 12:06:17

+0

\ n不起作用,它只是寫在控制檯上。 – Oliver 2012-02-29 23:03:11

相關問題