I have a simple model Foo
that represents a user preference and encapsulates an NSString
and an NSNumber
. I want to store an array of Foo
’s in user defaults so that they persist between launches of the application; and I’d like to display them in an table view such that the user can add, remove, and edit them. The solution to this seemed pretty straightforward with bindings, but it’s proving impossible for me to actually get working.
When my application launches I register with NSUserDefaults
a keyed archive of an array of initial Foo
’s. In my XIB I have an array controller with its content array bound to the shared user defaults controller’s values
controller key; with a key path of foos
; ‘Handles Content As Compound Value’ checked; and NSKeyedUnarchiveFromData
as the value transformer. The table view is then in turn bound to the array controller and the columns of the table to the properties of Foo
.
This works perfectly when Foo
’s are added and removed from the array—the foos
key in user defaults is updated to reflect the new contents of the array. The problem is that changes to the properties of an individual Foo
don’t similarly trigger the array to be written back to user defaults. I believe the reason for this is discussed in the ‘To-many Relationships’ section of ‘Registering Dependent Keys’ in the Key-Value Observing Programming Guide: changes to the array controller’s array itself are observed, but changes to properties of the contained elements aren’t.
Despite recognizing this as the problem I can’t for the life of me figure out what to actually do in order to make this work. When I observe a change on a Foo
what object do I need to inform and with what message such that the entire array is written back to user defaults—NSUserDefaults
, NSUserDefaultsController
, NSArrayController
? I wish the Apple documentation had more than a cursory mention of this problem and provided some actual example code to solve it—I’ve tried everything and I can’t find the magic incantation.
This is similar to How to get notified of changes to models via an NSArrayController but I can’t make the conceptual leap between what he’s doing with a custom view and the use of bind:toObject:withKeyPath:options:
.
Thanks! :)