从 Objective-C 中的 Core Data 元素获取和设置值?
我有一个包含两个实体的简单应用程序:
人员:
Attributes:
name
Relationships:
nativeLanguage: (<<-> Language.natives)
nonNativeLanguage: (<<-> Language.nonNatives)
语言:
Attributes:
name
Relationships:
natives: (<->> Person.nativeLanguage)
nonNatives: (<->> Person.nonNativeLanguage)
在人员的编辑屏幕上,我有一个表格显示集,用于列出为人员列出的非母语,以及一个供他们使用的下拉框选择另一种语言和用于将新语言添加到列表中的按钮。
我的目标是创建一个函数,如下所示:
- (IBAction)addNonNativeLanguage:(id)sender {
// tack the language to the end of the list on a many-many relationship
PersonEntry.nonNativeLanaguages = PersonEntry.nonNativeLanguages + sender;
}
并将操作附加到按钮。窍门是,虽然我知道如何分配和修改常规变量,但我不知道如何在 Interface Builder 之外修改 Core Data 的内容。我怎样才能在 Objective-C 中做到这一点?
I've got a simple application with two entities:
Person:
Attributes:
name
Relationships:
nativeLanguage: (<<-> Language.natives)
nonNativeLanguage: (<<-> Language.nonNatives)
Language:
Attributes:
name
Relationships:
natives: (<->> Person.nativeLanguage)
nonNatives: (<->> Person.nonNativeLanguage)
On the edit screen for people, I've got a table display set to list the non-native languages listed for the person, along with a drop box for them to choose another language and a button to add the new language to the list.
My goal is to create a function as follows:
- (IBAction)addNonNativeLanguage:(id)sender {
// tack the language to the end of the list on a many-many relationship
PersonEntry.nonNativeLanaguages = PersonEntry.nonNativeLanguages + sender;
}
and attach the action to the button. Trick is, while I know how to assign and modify regular variables, I have no idea how to modify the contents of Core Data outside of Interface Builder. How can I do it in Objective-C?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在我的所有核心数据模型实体类中,我有以下用于对多关系操作的代码:
此模板代码来自 Wolf Rentzsch 非常优秀的 mogenerator(在每次保存数据模型时自动生成它)。
另请注意,一对多关系的核心数据后端是无序的。如果你想保持数据的顺序,你必须自己做。
In all my Core Data model entity classes, I have the following code for to-many relationship manipulation:
This template code is from Wolf Rentzsch's very excellent mogenerator (which automatically generates it appropriately upon every save of the data model).
Also, note that the Core Data backend for to-many relationships is unordered. If you want to keep an order to your data, you have to do it yourself.
您首先必须找到所需的托管对象实例/记录。快速而肮脏的方法是询问显示人员对象的界面元素它拥有哪个对象。
获得使用的对象后,请使用关系名称调用
mutableSetValueForKey:
。这为您提供了所有相关语言的可变集。然后,您获取正确的语言对象并使用标准 NSMutableSet 方法将其添加到集合中。You will first have to find the managedObject instance/record you want. The quick and dirty way is to ask the interface element that is displaying the person object which object it has.
Once you have the object you use call
mutableSetValueForKey:
with the name of the relationship. This gives you a mutable set of all the related languges. You then fetch the proper language object and add it to the set using the standard NSMutableSet methods.