Search code examples
objective-carrayscocoansarraycontrollerkey-value-observing

How to observe changes to the items contained by an NSArrayController


I have an object containing an NSMutableArray called pointValue and several methods including setPointValue. When the latter method is invoked it triggers another method saveTable which saves pointValue to a file (its a csv but does matter not here as the save methods work). I now have nib file which contains a NSTableView and NSArrayController which is connected to the array in the object. With a button in the nib is pressed it triggers the NSArrayController remove: method, removing the selected item, accessing the setPointValue which saves the new array.

This all works perfectly, my problem begins when I edit a cell in the table manually and press enter, the array is changed but setPointValue is not triggered and thus the array is not saved to file.

I am absolutely god-smacked why setPointValue is not evoked. Do i have to bind the array control or the table columns to something?


Solution

  • Your NSArrayController is only observing its content array. You want to observe values of the objects in that array, which is not the same thing.

    I'd strongly encourage you to read all the documentation on Key-Value Observing and Cocoa Bindings.

    You'll see that you'll need to observe items as they're added to your setPointValue array and stop observing them when they're removed. You can do this by creating indexed collection accessor methods for your setPointValue and setting up or tearing down observing for items added and removed therein. You'll also need to react to receiving notification of the changes to your observed items to trigger your save method.

    Sosborn is correct - this is effectively a duplicate of this question. See the accepted answer the OP provided himself for the most direct solution (better than my original answer to this question).