I want to be able to create a new entity in the database after the user specifies the attributes in app. Is this possible?
Asked
Active
Viewed 299 times
-2
-
This is quite broad. Have a look at http://stackoverflow.com/questions/16131517/dynamically-creating-a-core-data-model-at-runtime, http://stackoverflow.com/questions/29908435/create-core-data-entities-dynamically-during-runtime, http://stackoverflow.com/questions/6379025/customize-core-data-model-at-runtime. – Martin R Aug 02 '15 at 18:42
-
To be more specific I'm creating an app that allows users to create custom workouts and then log their data. So after they create a workout I would need to create a core data entity with attributes corresponding to each exercise in the workout. – NN2 Aug 02 '15 at 18:57
1 Answers
0
You can't create new entities on the fly while using your persistent store. You create new instances of existing entities. Think of an entity kind of like you'd think of a class or a struct; you don't usually declare new classes or structs while your app is running but you do create new instances of each.
The most common way to create a new instance of an entity is with NSEntityDescription
's method, insertNewObjectForEntityForName(_, inManagedObjectContext:)
.
If you need an entity that defines a workout that has a customizable list of exercises, the best way would be:
- Create a generic
Workout
entity that doesn't define any exercises directly - Create an
Exercise
entity that defines one exercise. - Add a to-many relationship from
Workout
toExercise
so that an instance ofWorkout
can have any number of relatedExercise
instances.

Tom Harrington
- 69,312
- 10
- 146
- 170