Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Customize core data model at runtime?

I want a model which could be customized by the user. Is it possible with core data or are there better solutions?

Thanks matchi

Ps: it is an application for mac os!

like image 201
matchi Avatar asked Jan 20 '23 11:01

matchi


2 Answers

This is explained under "Creating the Managed Object Model" of Apple's Core Data Utility Tutorial. In general, once you have a reference to a managed object model, you can use the NSEntityDescription and NSAttributeDescription classes to customize the entities and their attributes in the managed object model.

Note, however, that in most cases once you modify a managed object model it will no longer be compatible with existing persistent data stores, meaning that you will then have to migrate data from your old persistent store to your new one. This is definitely not an endeavor to be taken lightly.

Of course, as mentioned in the comments, Core Data can also migrate data automatically, a process known as lightweight migration. In general, though, to do so

Core Data needs to be able to find the source and destination managed object models itself at runtime. (Core Data searches the bundles returned by NSBundle’s allBundles and allFrameworks methods.) It must then analyze the schema changes to persistent entities and properties and generate an inferred mapping model. For Core Data to be able to do this, the changes must fit an obvious migration pattern, for example:

  • Simple addition of a new attribute
  • A non-optional attribute becoming optional
  • An optional attribute becoming non-optional, and defining a default value

Does this fit your use case, or do you want to allow your users to change the managed object model in ways that would make lightweight migration impossible?

In any case, I highly recommend that you read through the following documents before you try to allow your users to modify Core Data models.

  • Core Data Programming Guide
  • Core Data Model Versioning and Data Migration Programming Guide
  • Core Data Utility Tutorial
  • NSPersistentDocument Core Data Tutorial
like image 122
Chris Frederick Avatar answered Jan 28 '23 09:01

Chris Frederick


See the NSManagedObjectModel reference page...

Managed object models are editable until they are used by an object graph manager...However, once a model is being used, it must not be changed...

I'd say this is definitely an advanced Core Data topic (and Core Data itself is already a pretty advanced topic), not to be undertaken lightly. I'm not sure that any data already stored in a data store would be useful (or even useable) if you let the user modify the model.

like image 45
Caleb Avatar answered Jan 28 '23 10:01

Caleb