Search code examples
cocoacocoa-bindingskey-value-observingnscollectionviewmonomac

Data-binding in a NSCollectionView


I've got a NSCollectionView for which I do have a dataArray and a selectedIndexes NSIndexSet defined in it's File's Owner. (Since I'm working with MonoMac on that project I've had some trouble working with a simple NSArrayController and so I decided to implement the source myself.) When initializing my controller I'm adding some data (NSMutableDictionarys) to the dataArray. When the application shows it's window all the data I just added is being displayed nicely.

The problem is that changes to the data source do not affect the interface in any way. Shouldn't the interface update itself automatically when I add, change or remove an item from the data source since I bound the values using it's corresponding keys?

Am I missing something? Any thoughts on that?

Thanks a lot
–f


Solution

  • When binding to a to-many relationship of you data source you have to make sure that the data source is Key-Value Observing compliant for this property. It is not enough to have a public property to a mutable collection, like an NSMutableArray.

    In the implementation of the data source, you have to use the methods from the NSKeyValueObserving protocol to advertise the changes you make (using willChange:valuesAtIndexes:forKey: for to-many relationships).

    If performance is less important than a simple implementation you can also use an (immutable) NSArray for the property and always assign a new array when data changes. This way you will not get the nice animations for added or removed objects, though.