How to create a nice -description method that angrily resembles NSArray

The -description method for NSArray will insert 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 like this for my own classes (using a script I am writing).

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

I have 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 as soon as one of the properties is an NSArray or another object using the 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 can I get additional nesting levels?

+1


a source to share


3 answers


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

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

      



Set the indentation to 1 so that your nested array or dictionary will indent whatever it prints by the specified amount.

+8


a source


This actually works for my purposes:



[[self.prop2 description] stringByReplacingOccurrencesOfString:@"\n" withString:@"\n    "]

      

+1


a source


You may need to stop using description

c NSArray

. Perhaps you should write a method to iterate over the array and indent as needed by appending to NSString

. You will probably have to use NSMutableString

and pass it so that lines can be appended to it.

Edit

Based on your comment, I would say to use methods objc_*

to think about which object was passed to your debug method. From there, you can pull all properties or instance variables and step through them. You can also use a conditional expression to check the type of ivar, and if it is a standard collection class like NSArray

or NSDictionary

, iterate over it yourself to output the data in the format you want (and then of course handle other object types and all primitives in your own way) ...

0


a source







All Articles