Search code examples
objective-ccocoaloggingpretty-print

How do I create a nice -description method that nests recusively like NSArray


The -description method for NSArray will nest recursive calls as in:

2009-05-15 14:28:09.998 TestGUIProject[29695:813] (
    a, // Array1 item 1
        ( // Array2, a second array, nicely indented another 4 spaces
        a // Item in Array2
    ) // End of Array2
) // End of Array1

I want to do something similar for my own custom classes (using a script I'm writing).

What I don't know is how to add the extra level of indentation when the recursively called object adds new lines of its own.

What I have is the following:

- (NSString *)description {
    return [NSString stringWithFormat:@"{{{\n"
            @"    prop1: %@\n"
            @"    prop2: %@\n"
            @"    prop3: %@\n"
            @"    prop4: %@\n"
            @"}}}",
            self.prop1,
            self.prop2,
            self.prop3,
            self.prop4];
}

But this breaks down as soon as one of the properties is an NSArray or another object using this same description format, because it doesn't nest nicely.

Instead you get:

2009-05-15 14:25:50.899 TestApp[29636:813] {{{
    prop1: SomeValue1
    prop2: ( // Prop 2 is an Array of strings
    "String1", // Note no additional level of indentation as in the NSArray example
    "String2",
    "String3",
    "String4"
)
    prop3: SomeValue3
    prop4: SomeValue4
}}}

How do I do I get the additional levels of nesting?


Solution

  • What you want is this function, available on NSArray and NSDictionary:

    - (NSString *) descriptionWithLocale: (id) locale indent: (NSUInteger) level;
    

    Specify an indent of 1 to have your nested array or dictionary indent everything it prints by the specified amount.