保存一对多关系
我开始学习和练习一些 CoreData,但没有编程经验。
在网上搜索、查找苹果示例并阅读了一些书籍之后,我仍然停留在一个点上。
我有两个具有相互关系的实体(费用和月份),称为“monthsOfExpense”和“expensesOfmonth”,并且我在表格中显示单个月份的费用。
我的问题是插入新费用并保存它们:我有一个插入新费用的视图,用户可以在其中插入费用名称、费用值和费用有效月份(我希望与 MonthsOfExpense 关系相关联)。
我可以保存费用实体的名称和值,从文本字段中获取字符串和 NSDecimal 数字。
我的问题是如何将该费用与特定月份或几个月关联起来?如何将 textField.text 保存为关系,指示费用属于哪个月份?
我从一个文本字段开始,用户可以在其中插入一个月,假设费用仅在一个月内有效(出于学习目的和简化目的)。
我的想法是允许用户选择几个月(可能使用另一个具有可选月份的 tableView)并将费用与不同月份关联。
我知道关系以 NSSet 的形式出现,但我无法同时保存视图中的属性和关系。
希望已经消除,非常感谢您的帮助。
I'm starting to learn and practice some CoreData, with no programming experience.
After searching in Web, looking for Apple samples and reading some books, I´m still stucked in one point.
I have two entities (Expenses and Month) with reciprocal relationships called "monthsOfExpense" and "expensesOfmonth" and I'm showing in a tableView the expenses of a single month.
My problem is to insert new expenses and save them: I've a view to insert new expenses where the user can insert the name of Expense, the value and the months that expense is valid (associated with the monthsOfExpense relationship, i hope).
I'm ok saving the name and the value of Expense entity, taking the string and NSDecimal number from the textFields.
My problem is how to associate that expense to a particular or several months? How can I save a textField.text as a relationship, indicating to what month an Expense belongs?
I'm starting with a textField where the user can insert a month, assuming that an Expense is valid for one month only (for learning purposes and simplification).
My idea is to allow the user to select several months (using maybe another tableView with selectable months) and association of an Expense to different months.
I know that a relationship comes as a NSSet, but I'm not being competent to save the attributes and the relationship from a View, at the same time.
Hope was cleared and many thanks in advance for trying to help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
好的。在核心数据中,您定义“费用”实体,创建与“月份”实体的关系。现在为这两个实体创建类文件。然后你用它
OK. In Core data, you define your "Expense" entity, create a relationship to "Month" entity. Now create class files for these 2 entities. Then you use it by
在您的情况下,您可以预定义 12 个“月份”对象,将月份名称指定为文本属性。
然后您可以使用 NSFetchRequest 查找这些月份对象。 将相关月份对象添加到您的费用中。
使用然后保存您的托管对象上下文
In your situation, you can predefine 12 "Month" objects, giving the month name as the text property.
Then you can lookup these month objects using NSFetchRequest. Add the relevant month objects to your expense using
Then save your managed object context.
您向托管对象发送消息以了解其 mutableSetValueForKey:RelationshipKey,
然后将多对托管对象添加到该集合中。 CoreData完成了关系数据的另一半。
You message the managed object for its mutableSetValueForKey:RelationshipKey,
then you add the to-many managed objects to that set. CoreData completes the other half of the relationship data.