Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create Core Data entities dynamically during runtime

I need to be able to create new core data entities during runtime. I've written the code to create the objects programmatically, however, I can't add the entities during runtime as the model is immutable.

My problem is similar to this post, however there is no satisfactory answer: How to dyanmic create a new entity (table) via CoreData model?

The documentation regarding changing the core data model explains:

Managed object models are editable until they are used by an object graph manager (a managed object context or a persistent store coordinator). This allows you to create or modify them dynamically. However, once a model is being used, it must not be changed. This is enforced at runtime—when the object manager first fetches data using a model, the whole of that model becomes uneditable. Any attempt to mutate a model or any of its sub-objects after that point causes an exception to be thrown. If you need to modify a model that is in use, create a copy, modify the copy, and then discard the objects with the old model.

However, I'm unclear on what exactly this is saying--that the whole core data model can't be changed once the persistent store coordinator has been used or the attributes/etc of the individual entities can't be changed.

To be clear, I do not want to change the attributes of my current entities, I simply want to add new entities. It just seems weird to me to have to use migration to add new entities.

Any thoughts?

Thanks!

like image 950
Synergy807 Avatar asked Aug 05 '26 13:08

Synergy807


1 Answers

The documentation is pretty clear.

  1. Copy the model.
  2. Apply your changes to the new copy.
  3. Destroy your old MOC, Persistent Store Coordinator, and all objects created from those.
  4. Apply a migration, if necessary.
  5. Create a new Core Data Stack (MOC, PSC, etc) using your updated model.

The migration could be a sticking point, but it should be do-able.

like image 151
Holly Avatar answered Aug 08 '26 02:08

Holly