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?

  • How to resize a cell.imageView in a TableView and apply tintColor in Swift
  • NSNumberFormatter numberFromString returns null
  • UICollectionView with Paging Enable
  • in-app purchase Sandbox Environment loop
  • Customizing subtitles with AVPlayer
  • Swift/iOS: How to use inout parameters in functions with AnyObject/Any or Pointers
  • 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
    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?


    Solutions Collect From Internet About “Create Core Data entities dynamically during runtime”

    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.