将表示一对多关系的 NSSet 绑定到 NSArrayController 的选择
这是场景。有两个CoreData模型对象A和B,它们之间的关系是A
有多个B
,由属性setOfBs
表示。我想显示两张表,一张列出所有 A(表 1),另一张列出所有 B(表 2)。当用户选择表 1 中的项目时,表 2 中的选择会发生变化,以反映表 1 中所选 A 的 setOfBs
值。表的内容不会改变,只有选择发生变化。如果表 1 中的选择发生变化,它会更改 setOfBs
以反映这一点。
这可以使用绑定来完成吗?或者需要自定义逻辑吗?
Here's the scenario. There are two CoreData model objects, A and B, and the relationship between them is that A
has-many B
, represented by the property setOfBs
. I'd like to display two tables, one listing all the As (Table 1), another listing all the Bs (Table 2). As the user selects items in Table 1, the selection in Table 2 changes to reflect the value of setOfBs
of the A selected in Table 1. The content of the table doesn't change, only the selection changes. And if the selection in Table 1 changes, it would change the setOfBs
to reflect that.
Can this be accomplished using bindings? Or would custom logic be required?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我相信您必须编写额外的逻辑才能使这种方法发挥作用。原因如下: NSArrayController 的选择绑定(以及绑定到它们的所有 UI 对象)基于选择索引,但是当您拥有 A 类型的对象时,它会提供一组 B 对象。。假设您有一个用于 As 的数组控制器和一个用于 Bs 的数组控制器,您需要一种方法来从这些对象获取它们在 B 数组中的索引,以便设置B 的数组控制器的选择。这不是很难编写的代码,但我不相信您能够单独使用绑定来完成此操作。
也就是说,正如您在评论中推测的那样,这似乎不是编辑这种关系的好方法。在常见情况下,TableView 选择是UI 状态,而不是模型 状态。如果您构建一个像您所描述的那样的 UI,UI 状态和模型状态就会变成同一件事。我并不是说这是不可能的,或者本质上是不好的,但这并不是做这类事情的真正“标准”方式。一种常见的模式如下所示:
即使是这样的方法也需要额外的逻辑,因为出现不是一种无需编写代码即可绑定到“不在所选 A 的 setOfB 中的所有 B”的方法(开箱即用)。同样,编写代码并不困难,但我不清楚这是否可以单独使用绑定来完成。我可能是错的,但这就是我对情况的解读。
I believe you will have to write additional logic to get this approach to work. Here's why: The selection bindings for NSArrayControllers (and all the UI objects that bind to them) are based on selection indexes but when you have an object of type A, it vends a set of B objects. Assuming you have an array controller for As and an array controller for Bs, you need a way to get from those objects to their indexes in the array of Bs in order to set the selection of the array controller for B. This isn't hard code to write, but I don't believe you'll be able to do this with bindings alone.
That said, as you speculated in your comment, this doesn't seem like a good way to edit this relationship. In the common case, TableView selection is UI state, and not model state. If you build a UI like you describe, UI state and model state become the same thing. I'm not saying it's impossible, or inherently bad, but it's not really a "standard" way to do this sort of thing. One common pattern looks like this:
Even an approach like this will require additional logic, because there appears to not be a way (out of the box) to bind to "All Bs not in the selected A's setOfBs" without writing code. Again, not difficult code to write, but it's not clear to me that this can be done with bindings alone. I could be wrong, but that's my reading of the situation.