Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct implementation of NSObject description method for nested classes containing collections

Tags:

iphone

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.

like image 812
maciejs Avatar asked Dec 02 '10 15:12

maciejs


1 Answers

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.

like image 192
w-m Avatar answered Sep 17 '22 13:09

w-m