With my own classes, I usually override -(NSString *)description method to ease debugging. However when invoking description on a class that I implemented that calls recursively description method from my other classes, all formatting characters from the 'deeper' classes are escaped. That makes any pretty printing difficult to implement. Here's an example to make it clearer:
@interface Foo {
NSArray *barsArray;
}
@end
@implementation Foo
- (NSString *)description {
return [NSString stringWithFormat: @"foo contents: %@", barsArray];
}
@interface Bar {
NSString *s1;
NSString *s2;
}
@implementation Bar
- (NSString *)description {
return [NSString stringWithFormat: @"s1: %@\ns2: %@", s1, s2];
}
In this case, the \n newline characters from description of class B will get escaped in the output of class A description method. Any idea how to get rid or circumvent this behaviour? It's especially annoying when printing nested classes that all contain collections.
You can always make use of the nice formatting that the standard containers come with. For example, your Bar description could be:
- (id)containerDescription {
return [NSDictionary dictionaryWithObjectsAndKeys:s1, @"s1", s2, @"s2", nil];
}
- (NSString *)description {
return [self.containerDescription description];
You can now do the following on Foo:
- (NSString *)description {
NSArray *desc = [barsArray valueForKey:@"containerDescription"];
NSDictionary *descriptionDictionary =
[NSDictionary dictionaryWithObjectsAndKeys:desc, @"foo contents", nil];
return [descriptionDictionary description];
}
The solution is not optimal of course, as you have to have a second method and have to call the containerDescription on higher levels, but it's the only one I found yet.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With