在 Cocoa 中如何从这个可变数组更新 NSTableView ?

发布于 2024-10-20 21:38:56 字数 899 浏览 6 评论 0 原文

在我的应用程序中,我有一个 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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

烂柯人 2024-10-27 21:38:56

-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 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.

递刀给你 2024-10-27 21:38:56

您正在使用 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!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文