如何观察 NSArrayController 包含的项目的变化
我有一个对象,其中包含一个名为 pointValue
的 NSMutableArray 和包括 setPointValue
在内的多个方法。当调用后一个方法时,它会触发另一个方法 saveTable
,该方法将 pointValue
保存到文件(它是 csv,但在这里并不重要,因为保存方法有效)。 我现在有 nib 文件,其中包含连接到对象中的数组的 NSTableView
和 NSArrayController
。 按下笔尖中的按钮,它会触发 NSArrayController
remove:
方法,删除所选项目,访问保存新数组的 setPointValue
。
这一切都很完美,当我手动编辑表中的单元格并按 Enter 键时,我的问题开始了,数组发生了更改,但未触发 setPointValue ,因此数组未保存到文件中。
我真的很惊讶为什么 setPointValue 没有被唤起。我是否必须将数组控件或表列绑定到某些东西?
I have an object containing an NSMutableArray
called pointValue
and several methods including setPointValue
. When the latter method is invoked it triggers another method saveTable
which saves pointValue
to a file (its a csv but does matter not here as the save methods work).
I now have nib file which contains a NSTableView
and NSArrayController
which is connected to the array in the object.
With a button in the nib is pressed it triggers the NSArrayController
remove:
method, removing the selected item, accessing the setPointValue
which saves the new array.
This all works perfectly, my problem begins when I edit a cell in the table manually and press enter, the array is changed but setPointValue
is not triggered and thus the array is not saved to file.
I am absolutely god-smacked why setPointValue is not evoked. Do i have to bind the array control or the table columns to something?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的 NSArrayController 仅观察其内容数组。您想要观察该数组中的对象的值,这不是一回事。
我强烈建议您阅读 键值观察和Cocoa绑定。
您会发现,您需要在将项目添加到 setPointValue 数组时对其进行观察,并在将其删除时停止观察它们。您可以通过创建索引集合访问器方法来完成此操作 为您的 setPointValue 并设置或拆除其中添加和删除的项目的观察。您还需要对 接收观察项目的更改通知以触发保存方法。
索斯伯恩是正确的 - 这实际上是 的重复这个问题。请参阅OP自己提供的已接受答案以获得最直接的解决方案(比我对这个问题的原始答案更好)。
Your NSArrayController is only observing its content array. You want to observe values of the objects in that array, which is not the same thing.
I'd strongly encourage you to read all the documentation on Key-Value Observing and Cocoa Bindings.
You'll see that you'll need to observe items as they're added to your setPointValue array and stop observing them when they're removed. You can do this by creating indexed collection accessor methods for your setPointValue and setting up or tearing down observing for items added and removed therein. You'll also need to react to receiving notification of the changes to your observed items to trigger your save method.
Sosborn is correct - this is effectively a duplicate of this question. See the accepted answer the OP provided himself for the most direct solution (better than my original answer to this question).