Search code examples
cocoanstableviewcocoa-bindings

How does updating NSTableView from this mutable array work in Cocoa?


In my application, I have an NSTableView which should contain a list of files. I have a button that is used to open an dialog and programmatically add files to this list. For some time, I could not get the table view to update when I was adding files, as I was using the following code:

[self.newPackage.files addObject:fileURL];

It makes sense to me now that this doesn't work. As I understand it, the above line of code would be changing the mutable array "behind the controller's back."

I was able to piece together a working solution, largely from this question, with the following code:

NSMutableArray *bindingsCompliantArray = [[self valueForKey:@"newPackage"] mutableArrayValueForKey:@"files"];
[bindingsCompliantArray addObject:fileURL];

However, I don't understand how this works. bindingsCompliantArray is not used anywhere else either. I've looked at the documentation for mutableArrayValueForKey, but it's not making it any clearer. Is there anyone that could help explain how this is working?


Solution

  • The ‑mutableArrayValueForKey: method returns a proxy array that you can treat as if it's the original array, with the added bonus that changes to the array are observed by any KVO observers watching the array.

    NSController subclasses such as NSArrayController use Key-Value Observing to monitor changes to the objects they observe.

    When you receive a proxy array via this method, NSMutableArray methods such as ‑addObject: will be noticed by observers, whereas with a standard array this is not the case.