saving a to-many-relationship

十年热恋 提交于 2019-12-13 05:34:23

问题


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.


回答1:


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

Expense *expense1 = [NSEntityDescription insertNewObjectForEntityName:@"Expense" ....
Month *month1 = [context executeFetchRequest:......];
expense1.month = month1;
...
[context save];



回答2:


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

[expense addMonthObject:month]

Then save your managed object context.




回答3:


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.



来源:https://stackoverflow.com/questions/5261853/saving-a-to-many-relationship

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!