如何使用核心数据实现这一点 [英] How To Achieve This Using Core Data
问题描述
这是我的数据模型的图片:
Here is a picture of my data model:
我有一个视图,其中用户可以输入一个数字的重量&代表。如何使用NSFetchedResultsController(或更好的选项)将其保存为Set的实例。
I have a view where the user can enter a number for weight & reps. How can I use NSFetchedResultsController (or a better option) to save this as an instance of "Set".
然后我想让用户能够做多个Set 用于特定的练习。用户可能选择做5种不同的练习。我希望总共练习为1会话。
Then I want the user to be able to make multiple "Set" for a particular "Exercise". The user might choose to do 5 different "Exercise". I want the total of exercises to be as 1 "Session".
并且会话将与时间戳一起存储。
And "Session" will be stored with a timestamp. That way I can search and bring up data from today, or within 30 days, etc.
推荐答案
首先,设置您的核心数据栈使用苹果的模板或其他示例代码(我通常使用自定义单例为此)。您将创建NSManagedObjectModel,NSManagedObjectContext和NSPersistentStoreCoordinator的实例。
First, set up your "Core Data stack" using Apple's templates or other example code (I usually use a custom singleton for this). You will create instances of NSManagedObjectModel, NSManagedObjectContext, and NSPersistentStoreCoordinator.
要创建新的托管对象,我喜欢使用NSEntityDescription类方法 insertNewObjectForEntityForName:inManagedObjectContext :
(真的我使用发电机,但这是它使用的)。
To create new managed objects, I like to use the NSEntityDescription class method insertNewObjectForEntityForName:inManagedObjectContext:
(really I use mogenerator, but that's what it uses).
您可以将所有对象称为NSManagedObject,并使用 setValue:forKey:
但我建议为您的实体生成自定义类文件(Xcode可以做这个或尝试mogenerator)。
You can refer to all your objects as NSManagedObject and use setValue:forKey:
, etc; but I recommend generating custom class files for your entities (Xcode can do this or try mogenerator).
例如(假设你生成类文件和NSManagedObjectContext对象是moc
For example (assuming you generate class files and NSManagedObjectContext object is "moc" here):
Set *set = [NSEntityDescription insertNewObjectForEntityForName:@"Set" inManagedObjectContext:moc];
set.weight = 100;
set.reps = 10;
NSMutableSet *sets = [NSMutableSet set];
[sets addObject:set];
Exercise *exercise = [NSEntityDescription insertNewObjectForEntityForName:@"Exercise" inManagedObjectContext:moc];
exercise.relationship = sets; // you should name this relationship something like "sets"
然后,他们到一个集合并分配该集合到会话的多对练习关系(再次,练习将是一个更好的名称)。
Then, you can build up exercises and add them to a set and assign that set to the Session's to-many Exercises relationship (again, "exercises" would be a better name).
要保存,只需调用 save:
。
此外,我注意到你的模型没有反向关系。强烈建议您始终具有反向关系。
Also, I noticed that you don't have inverse relationships in your model. It is strongly recommended that you always have inverse relationships.
这篇关于如何使用核心数据实现这一点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!