Search code examples
objective-ccocoansviewnswindow

Get ALL views and subview of NSWindow


Is there a way I can get ALL the views and subviews and subviews of these subviews (you get the idea...) of an NSWindow?

Thanks.


Solution

  • Here is a category on NSView:

    @interface NSView (MDRecursiveSubviews)
    - (NSArray *)md__allSubviews;
    @end
    
    @implementation NSView (MDRecursiveSubviews)
    
    - (NSArray *)md__allSubviews {
        NSMutableArray *allSubviews = [NSMutableArray arrayWithObject:self];
        NSArray *subviews = [self subviews];
        for (NSView *view in subviews) {
            [allSubviews addObjectsFromArray:[view md__allSubviews]];
        }
        return [[allSubviews copy] autorelease];
    }
    
    @end
    

    With a quick nib file I created with a view hierarchy, it printed this:

    [RecursiveSubviewsAppDelegate awakeFromNib] allSubviews == (
        "<NSView: 0x10390dfd0>",
        "<NSView: 0x103c07ae0>",
        "<NSView: 0x100129cc0>",
        "<NSButton: 0x100115ce0>",
        "<NSButton: 0x100116900>",
        "<NSButton: 0x1001165c0>",
        "<NSButton: 0x100116130>",
        "<NSButton: 0x100114ad0>",
        "<NSButton: 0x100115910>",
        "<NSButton: 0x100115090>",
        "<NSScrollView: 0x103b07a30>",
        "<NSClipView: 0x103b07d40>",
        "<NSTextView: 0x103b083c0>\n
    Frame = {{0.00, 0.00}, {159.00, 58.00}},
    Bounds = {{0.00, 0.00}, {159.00, 58.00}}\n
    Horizontally resizable: NO, Vertically resizable: YES\n
    MinSize = {159.00, 58.00}, MaxSize = {463.00, 10000000.00}\n",
        "<NSScroller: 0x1001145b0>",
        "<NSScroller: 0x100114840>",
        "<NSScrollView: 0x10390ea00>",
        "<NSClipView: 0x10390ef10>",
        "<NSTableView: 0x10390f570>",
        "<NSScroller: 0x103b06f10>",
        "<NSScroller: 0x103b07460>",
        "<NSClipView: 0x1039105d0>",
        "<NSTableHeaderView: 0x103910300>",
        "<_NSCornerView: 0x103911c20>"
    

    One note of concern I should add is that it's unclear to me how this would be useful, except as a debugging tool. But even then, there are probably easier ways of doing things.