Search code examples
objective-ccocoansmutablearraynsmutabledictionarynsarraycontroller

Best way to add/remove to an NSMutableArray managed by an NSArrayController


I've got a NSMutableArray (containing NSMutableDictionary instances) bound to an NSArrayController (the NSArrayController is in turn bound to NSTableView columns).

What is the most Cocoa-, and KVO- friendly way of, programmatically :

  • adding a new empty object (NSMutableDictionary) to the array?
  • removing currently selected object? (after removing, the previous item - if exists - should be selected)

I've always been doing this in a way I don't particularly like - and I'm sure it's not the best way around (too many lines of code for something so simple : in Cocoa that indicates a wrong take on the subject :-)).


My code (quite an overkill, actually) :


Adding to the Array

NSMutableArray* oldParams = [paramsArray mutableCopy];

[oldParams addObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:@"Parameter",@"Parameter",@"",@"Value", nil]];
[self setParamsArray:oldParams];

[paramsController setSelectionIndex:[paramsArray count]-1];

Removing currently selected object from the Array

if ([paramsArray count]>0)
{
    int s = [paramsController selectionIndex];

    NSMutableArray* oldParams = [paramsArray mutableCopy];

    [oldParams removeObjectAtIndex:s];

    [self setParamsArray:oldParams];

    if (s<=[paramsArray count]-1)
        [paramsController setSelectionIndex:s];
    else
        [paramsController setSelectionIndex:[paramsArray count]-1];
}

So, what are your opinions on that?


Solution

  • You have to think of your array as the controller's backing store, and that it's managing it for you.

    Adding an object:

    [[self accountsArrayController] addObject:accountDictionary];
    

    Removing the currently selected object:

    [[self accountsArrayController] remove:nil];
    

    You'll have to write another line or two to make that previous item selected, but that's an exercise I leave to you.