开发者

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?


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.


You are using the addObject method to update the array and I think that the trouble remains there. Try to update it by setting a NEW array with the new value. It should work! =D

Good luck!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜