在我的应用程序中,我有一个 NSTableView,其中应包含文件列表。我有一个按钮,用于打开对话框并以编程方式将文件添加到此列表中。一段时间以来,当我添加文件时,我无法更新表视图,因为我使用了以下代码:
[self.newPackage.files addObject:fileURL];
现在这对我来说是有意义的,因为这不起作用。据我了解,上面的代码行将“在控制器背后”更改可变数组。
我能够拼凑出一个可行的解决方案,主要来自 这个问题,带有以下代码:
NSMutableArray *bindingsCompliantArray = [[self valueForKey:@"newPackage"] mutableArrayValueForKey:@"files"];
[bindingsCompliantArray addObject:fileURL];
但是,我不明白这是如何工作的。 bindingsCompliantArray 也没有在其他地方使用。我查看了 mutableArrayValueForKey 的文档,但它并没有使它变得更清晰。有没有人可以帮助解释这是如何工作的?
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?
发布评论
评论(2)
-mutableArrayValueForKey:
方法返回一个代理数组,您可以将其视为原始数组,还有一个好处是,任何观察该数组的 KVO 观察者都会观察到该数组的更改。NSController
子类(例如NSArrayController
)使用键值观察来监视它们观察的对象的更改。当您通过此方法接收代理数组时,
NSMutableArray
方法(例如-addObject:
)将被观察者注意到,而对于标准数组,情况并非如此。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 asNSArrayController
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.您正在使用 addObject 方法来更新数组,我认为问题仍然存在。尝试通过使用新值设置新数组来更新它。它应该有效! =D
祝你好运!
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!