swiftmacoscore-datansentitydescriptionnsmanagedobjectmodel

Finding the entities of a CoreData model at runtime


I have an macOS app being developed in Xcode (8.3.2) in SWIFT.

I have a CoreData model with a number of entities and an identifier (myidentifier).

I want to be able to identify the entities of the model programatically at runtime so that I can iterate through the entities and store data being sourced from a range of JSON files based on the data within the JSON file.

To date I have been creating entities and then writing a class for each entity to both save and fetch the data. It is working perfectly and as expected. However, if I continue like this I will end up with about 50 different entities and their associated class files (note that some while entities use a one to many relationship, the majority do not).

I would like to create a single class that will enumerate through the numerous entities of the model and store the relevant data (as well as its associated fetch routine).

I should also note that I am using NSManagedObject subclasses for each of the entities.

How do I obtain a NSManagedObjectModel reference to the model that I am using for the app? I can't seem to find the right mechanism to allow me to do this. Can I do this using the model identifier?

My thinking is that if I can then use entitiesByName I can make use of the resulting [String: NSEntityDescription] to then access my entities and enumerate as needed.


Solution

  • You could use mergedModel(from bundles: [Bundle]?) (see the documentation here, specfying Bundle.main to get the main bundle. Alternatively, your NSManagedObjectContext will have a reference to the persistentStoreCoordinator which will itself have a reference to the managedObjectModel.

    Note that NSManagedObjectModel has an entities property so you can use:

    for myEntity in myModel.entities { ... }
    

    rather than using entitiesByName.