Search code examples
objective-cmacosuitableviewnsarraycontroller

NSTableView get selected row


I have a table view connected to an array controller and am able to populate the table with data. I want to be able to select a row and a handler be called. I've tried

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath;

but am unable to call the handler.

Working on a Mac app in Objective-C. How do I hook up this handler correctly or should I be using something different?


Solution

  • You won't be using UIKit in a Mac application, instead you will use AppKit's NSTableView.

    Create a column:

    NSTableColumn * column = [[NSTableColumn alloc] initWithIdentifier:@"SomeColumnId"];
    column.headerCell.stringValue = NSLocalizedString(@"Column Name", nil);
    [_table addTableColumn:column];
    

    Set up the table:

    - (NSInteger)numberOfRowsInTableView:(NSTableView *)tableView {
        return _someArray.count;
    }
    
    - (id)tableView:(NSTableView *)tableView objectValueForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row
    {
        if ( [tableColumn.identifier isEqualToString:@"SomeColumnId"] )
        {
            return @"Some cell string"; // or _someArray[row][@"some_string_key"]
        }
    
        return nil;
    }
    
    -(void)tableViewSelectionDidChange:(NSNotification *)notification
    {
        if ( [[notification object] selectedRow] == 0 )
        {
            /// first row was selected. 
        }
    }