Skip to content

Instantly share code, notes, and snippets.

@douglashill
Last active August 29, 2015 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save douglashill/877144a266ffb5d5075f to your computer and use it in GitHub Desktop.
Save douglashill/877144a266ffb5d5075f to your computer and use it in GitHub Desktop.
NSObject recursive description category, for debugging trees (subviews, sublayers, child view controllers) or chains (superviews, next responders, superclasses).
@interface NSObject (DHRecursiveDescription)
- (NSString *)dh_recursiveDescriptionWithRecursion:(id (^)(id obj))recursion;
@end
@implementation NSObject (DHRecursiveDescription)
- (NSString *)dh_recursiveDescriptionWithRecursion:(id (^)(id obj))recursion
{
NSMutableString *string = [NSMutableString stringWithString:@"\n"];
[self dh_recursivelyAddDescriptionToString:string withPrefix:@"" recursion:recursion];
return string;
}
- (void)dh_recursivelyAddDescriptionToString:(NSMutableString *)string withPrefix:(NSString *)prefix recursion:(id (^)(id obj))recursion
{
[string appendFormat:@"%@%@\n", prefix, [self description]];
id const next = recursion(self);
if ([next respondsToSelector:@selector(countByEnumeratingWithState:objects:count:)]) {
for (id child in next) {
[child dh_recursivelyAddDescriptionToString:string withPrefix:[@"\t| " stringByAppendingString:prefix] recursion:recursion];
}
}
else {
[next dh_recursivelyAddDescriptionToString:string withPrefix:prefix recursion:recursion];
}
}
@end
// Tree example: logging all subviews of a view
UIView *view;
NSLog(@"%@", [view dh_recursiveDescriptionWithRecursion:^id(id obj) {
return [view subviews];
}]);
// Chain example: logging all superviews of a view, up to the window
UIView *view;
NSLog(@"%@", [view dh_recursiveDescriptionWithRecursion:^id(id obj) {
return [view superview];
}]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment