Last active
August 29, 2015 14:06
-
-
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).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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