Cocoa: The Subview Hierarchy

More useful code.. this time to print out the entire hierarchy of subviews below any particular view. For maximum usefulness, put this in a category* of UIView:

- (void)OP_printSubviewsOfView:(UIView*)view {
    static NSInteger depthCount = 0;

    NSArray *subview_array = [view subviews];

    NSMutableString *tabString = [NSMutableString 
                            stringWithCapacity:depthCount];
    for (NSInteger i = 0; i < depthCount; i++) {
        [tabString appendString:@" -- "];
    }
    NSLog(@"%@ %@",tabString,view);

    if (subview_array) {
        depthCount++;
        for(UIView *v in subview_array) {
            [self OP_printSubviewsOfView:v];
        }
        depthCount--;
    }
}

Note(*): Categories in Objective-C are very useful. They are also easy to create:

@interface UIView(Extras)
- (void)OP_printSubviewsOfView:(UIView*)view;
@end

@implementation UIView(Extras)
- (void)OP_printSubviewsOfView:(UIView*)view {
    // code
}
@end

But be careful. Read the chapter in the Objective-C 2.0 Programming Language document on them first. In fact, if you haven’t read that document from cover to cover, you should. It’s not that long.

Saturday, January 24, 2009