Search code examples
objective-cnsuserdefaultspreferencesnstableviewnsarraycontroller

Objective-C: How to populate an NSTableView from an NSArrayController, and save selected indexes with Shared Defaults Controller?


I have an NSTableView that I want to load it's value from an NSArrayController. The array is built dynamically, and has the potential to change. I also want to save the selected indexes in NSUserDefaults, ideally by binding to Shared User Defaults Controller, but I can't see how to make the happen in bindings. Is there a way to do this?

Expanding..

In my array, I have a instances of a custom class. I only want to display an NSString field, a name. This is a multiple-select table view. I'd like to have them saved as soon as they are changed.

I know how to save fields to preferences using the Shared User Defaults Controller though bindings. I know how to set the TableView to use an array controller to display the data I wanted displayed.

I just can't seem to do both at the same time.


Solution

  • Just bind the array controller's Selection Indexes to the Shared User Defaults Controller with a Controller Key of "values" and a Model Key Path of whatever you want to call it. You also need to choose the NSKeyedUnarchiveFromData value transformer. Then in your code when you want to retrieve the selected indexes, you could do this (here I'm just logging it, and I used the name "selIndxs" in my binding):

    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
    NSLog(@"%@",[NSKeyedUnarchiver unarchiveObjectWithData:[ud valueForKey:@"selIndxs"]]);