Search code examples
interface-buildernsuserdefaultsnstableviewcocoa-bindingsnsarraycontroller

Make NSTableView row editable when adding object with NSArrayController


I have a table column of NSTableView bound to to an NSArrayController in Interface Builder. The array controller is bound to Shared User Defaults Controller for the Content Array. I had to select Handles Content As Compound Value to make adding new objects work. Unfortunately, this disables the highlighting of the table row when I add: an object to the array. The object is added but the table row is not highlighted and you have to double-click where you think the row is to be able to edit it.

My goal is to add: a row to the table view using the array controller; then, have that row automatically be highlighted and editable for the user.

Attributes for the NSArrayController:

enter image description here

Bindings for the the NSArrayController:

enter image description here

Bindings for the TableView Column:

enter image description here


Solution

  • The workaround that I found here worked for me.

    You need to subclass NSArrayController and implement your own add: method

    //
    //  MyArrayController.h
    //
    
    #import <AppKit/AppKit.h>
    
    @interface MyArrayController : NSArrayController
    
    @end
    

    and

    //
    //  MyArrayController.m
    //
    
    #import "MyArrayController.h"
    
    @implementation MyArrayController
    
    
    - (void)add:(id)sender {
        [super add:sender] ;
    
        [self performSelector:@selector(selectLastObject)
                   withObject:nil
                   afterDelay:0.0] ;
    }
    
    - (void)selectLastObject {
        if ([self selectsInsertedObjects]) {
            NSArray* arrangedObjects = [self arrangedObjects] ;
            NSInteger nObjects = [arrangedObjects count] ;
            if (nObjects > 0) {
                [self setSelectionIndex:nObjects-1] ;
            }
        }
    }
    
    
    @end