How to Get Current First Responder from Window Controller in Cocoa?

A A picture A A · Jun 10, 2012 · Viewed 9.9k times · Source

I would like to find the first responder view in a window. To do this, I would like to implement a category like this:

    @implementation  NSView (ViewExtensions)
- (NSView *)findFirstResponder
{
    if ([self isFirstResponder]) {        
        return self;     
    }

    for (NSView *subView in [self subviews]) {
        NSView *firstResponder = [subView findFirstResponder];

        if (firstResponder != nil) {
            return firstResponder;
        }
    }

    return nil;
}

@end

The above code is based on this question/answer on SO: Get the current first responder without using a private API.

The problem, perhaps, is that NSResponder doesn't have an isFirstResponder method like UIResponder does. What is the equivalent for NSResponder?

If the method above is implemented as above, I of course get the debug message: "'NSView' may not respond to 'isFirstResponder'".

How do I make findFirstResponder work in Cocoa?

Further information: I would later like to use the above method in my window controller in some way like:

        NSArray *copiedObjects;
        if ([[self window]contentView] == MyTableView) {
            copiedObjects = [tableController selectedObjects];
        }
        if ([[self window]contentView] == MyOutlineView) {
            copiedObjects = [treeController selectedFolders];
        }

Answer

Ken Thomases picture Ken Thomases · Jun 10, 2012

What's wrong with -[NSWindow firstResponder], which returns the first responder directly?