开发者

How To Achieve This Using Core Data

开发者 https://www.devze.com 2023-02-28 04:42 出处:网络
Here is a picture of my data model: I have a view where the user can enter a number for wei开发者_如何学Goght & reps.How can I use NSFetchedResultsController (or a better option) to save this as

Here is a picture of my data model:

How To Achieve This Using Core Data

I have a view where the user can enter a number for wei开发者_如何学Goght & reps. How can I use NSFetchedResultsController (or a better option) to save this as an instance of "Set".

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.


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.

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).

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).

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).

To save, just call save: on your NSManagedObjectContext object.

Also, I noticed that you don't have inverse relationships in your model. It is strongly recommended that you always have inverse relationships.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号