I have two Core Data entities called PreviousWorkout
, and ExerciseData
. The PreviousWorkout
entity holds the following attributes: date
, workoutName
, and exercises
. exercises
is supposed to be an array of ExerciseData
. After making the class with Editor > Create NSManagedObject Subclass, I then did the same thing with the ExerciseData
entity.
I'm unsure whether or not this is the correct way of storing data using Core Data. My goal is to have a PreviousWorkout
which contains an array of ExerciseData
as well as date
and workoutName
.
The way I'm creating it in code is by creating a managedbjectContext
with:
let managedObjectContext = (UIApplication.sharedApplication().delegate as AppDelegate).managedObjectContext
Then I create a PreviousWorkout
array with:
let newItem = NSEntityDescription.insertNewObjectForEntityForName("PreviousWorkout", inManagedObjectContext: managedObjectContext!) as PreviousWorkout
I add all my stuff ( date
and workoutName
) to newItem
, then I attempt to create an array of ExerciseData with:
var exerciseData = NSEntityDescription.insertNewObjectForEntityForName("ExerciseData", inManagedObjectContext: managedObjectContext!) as [ExerciseData]
The program crashes at this point. I realize that this last line is very wrong but I'm not sure how to create an array of ExerciseData
. After creating the array I would like to append to it, and then set values for its attributes before setting the newItem.exercises
equal to the ExerciseData
object.
Is this the correct way of creating a Core Data object that contains an array? How do I create the array of [ExerciseData]
?
Thanks in advance
An entity is essentially a table so you would store many Workouts in it and create a Workout entity, not just a PreviousWorkout entity. Then you should have an Exercise entity and store many exercises in it. Then to store an "array" in Core Data, you make a relationship between the two entities (probably a many to many relationship because each workout can have many exercises and each exercise can be a part of many workouts). Then to add exercises to a workout object, you just append them to a Workout objects exercises
property which is an NSSet
and it points at Exercise objects.
So now you have many workout objects and exercise objects, you can fetch the previous workout by using a fetch request and sorting all of your workouts by date or whichever property you want to sort by and taking the first result of the fetch request.
You create a new exercise like so:
let exerciseData = NSEntityDescription.insertNewObjectForEntityForName("Exercise", inManagedObjectContext: managedObjectContext!) as Exercise
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.