When you build a Core Data NSManagedObjectModel in code, what must each entity and attribute set, and why should the process create the model only once?
answer
- name, class and properties
- undefined type is only for transients
- editable until first use
- one class, two entity descriptions
- Multiple NSEntityDescriptions claim the subclass
basics
~20 sEach NSEntityDescription needs a name, a managedObjectClassName and properties; each NSAttributeDescription needs a name, a real type, optionality and defaults. Build one shared model: a second one claiming the same subclass leaves Plant(context:) unable to pick its entity.
solid answer
~40 sA code-built model is what the `.xcdatamodeld` file compiles to, written by hand: create an `NSEntityDescription`, set `name` and `managedObjectClassName` (it defaults to `NSManagedObject`), and assign `properties`. Each `NSAttributeDescription` needs `name` and a `type` such as `.integer16`; the default undefined type is legal only for transient attributes. Set `isOptional`, which defaults to `true`, and `defaultValue`, then constraints such as `uniquenessConstraints`, and assign `entities` on an `NSManagedObjectModel`. The model can be edited only until a coordinator uses it; mutating it afterwards throws. Create it once, in a `static let`: two model instances claiming one subclass log "Multiple NSEntityDescriptions claim the NSManagedObject subclass", and `Plant(context:)` may pick the wrong entity.
code
swift · 39 linesimport CoreData
@objc(Plant)
final class Plant: NSManagedObject {
@NSManaged var speciesName: String
@NSManaged var wateringInterval: Int16
}
enum PlantModel {
// Built once per process; Core Data freezes it at first use.
nonisolated(unsafe) static let shared: NSManagedObjectModel = {
let plant = NSEntityDescription()
plant.name = "Plant"
plant.managedObjectClassName = NSStringFromClass(Plant.self)
let species = NSAttributeDescription()
species.name = "speciesName"
species.type = .string
species.isOptional = false
let interval = NSAttributeDescription()
interval.name = "wateringInterval"
interval.type = .integer16
interval.isOptional = false
interval.defaultValue = 7
plant.properties = [species, interval]
plant.uniquenessConstraints = [["speciesName"]]
let model = NSManagedObjectModel()
model.entities = [plant]
return model
}()
}
// Every container in the process, tests included, reuses the one model.
func makeContainer() -> NSPersistentContainer {
NSPersistentContainer(name: "Plants", managedObjectModel: PlantModel.shared)
}go deeper
Recall the three objects involved, the model, the entity description and the attribute description, and the minimum each one needs.
Explain the editable-until-first-use rule, the isOptional default, and why the class name must match the subclass's runtime name.
Recognise the multiple-entity warning in test logs at once and fix it with a single shared model rather than silencing it.
Choose between a model file and a code-built model for a shared framework by weighing tooling and codegen against reviewable Swift diffs.
## Why build a model in code The model editor compiles a `.xcdatamodeld` file into a `.momd` bundle that `NSManagedObjectModel(contentsOf:)` loads. Everything it describes can also be built directly from `NSManagedObjectModel`, `NSEntityDescription` and `NSAttributeDescription`. Teams do this for test targets that should not depend on an app bundle's resources, for a framework that defines its schema next to the code using it, and for models assembled at runtime. Apple's documentation describes the model editor as the usual route and code as possible when needed. ## What each object needs **An entity** (`NSEntityDescription`) needs at least: - `name`, the entity name used by fetch requests (`"Plant"`); - `managedObjectClassName`, the runtime class name; if it is not set, the framework uses `NSManagedObject`, so `NSStringFromClass(Plant.self)` (with `@objc(Plant)` on the class) is the safe value; - `properties`, the array of attribute (and relationship) descriptions; - optionally `uniquenessConstraints` and `indexes`; the header advises setting indexes last, because later changes to the entity's properties drop them. **An attribute** (`NSAttributeDescription`) needs: - `name`, matching the `@NSManaged` property; - a type: the Swift `type` property (`.string`, `.integer16`, `.binaryData`, available from iOS 15) or the older `attributeType` (`NSAttributeType`). The default, undefined, is legal only for transient attributes; - `isOptional`, which is `true` unless you set it, so a required attribute must say so; - `defaultValue` where the model should supply one; the model retains it rather than copying it; - for Transformable values, `valueTransformerName` and `attributeValueClassName`; for large data, `allowsExternalBinaryDataStorage`. Finally, `model.entities = [plant]` collects the entities, and `NSPersistentContainer(name:managedObjectModel:)` uses the model instead of looking for a file. How the container loads stores from there belongs to the lesson on setting up the persistent stack. ## Editable until first use A model and its entity and property descriptions are mutable only until an object graph manager uses them. The documentation states that once the model is associated with a persistent store coordinator, or the coordinator first fetches with it, any attempt to change it throws an exception. To vary a model that is in use, copy it, change the copy and stop using the old one. In practice, build the whole model inside one closure and never touch it again. The same freeze explains a common test failure: a helper that adds an attribute to a shared model after the first test has created a container throws on the second test. Build every variant you need before any container is created, or build separate models deliberately and accept the class-mapping rule below. ## One model per process `Plant(context:)` and `Plant.entity()` have to work out which entity the `Plant` class represents. The documentation says `init(context:)` is legal only on subclasses that represent a single entity in the model. If two model instances exist, for example because a test helper builds a fresh model for every test, or the model file is loaded again for each container, two entity descriptions claim one class: ```plaintext CoreData: warning: Multiple NSEntityDescriptions claim the NSManagedObject subclass 'Plant' so +entity is unable to disambiguate. CoreData: error: +[Plant entity] Failed to find a unique match for an NSEntityDescription to a managed object subclass ``` What follows is unreliable: `Plant(context:)` can create an object with the other model's entity, which the context's coordinator does not know. The cure: 1. Build the model once, in a `static let`, and pass it to every container, tests included. 2. Where several models genuinely coexist, insert with `NSManagedObject(entity:insertInto:)` and the entity taken from that context's own model, or use `NSEntityDescription.insertNewObject(forEntityName:into:)`. ## Comparing the two routes | Concern | `.xcdatamodeld` file | Code-built model | |---|---|---| | Visual editing and codegen | yes | no; write the `@NSManaged` subclass yourself | | Model versions for migration | added in the editor | each version built and kept in code | | Review in a pull request | XML diff | ordinary Swift diff | | Risk of a second instance | loading the file twice | building it twice | Either way the result is the same kind of object: an `NSManagedObjectModel` whose entities, attributes and constraints Core Data reads identically, so the choice is about tooling and review, not runtime behaviour.
- What happens if you add an attribute to a Core Data model after its container has loaded the store?The change throws an exception. A model becomes immutable once a persistent store coordinator uses it; to change it you copy the model, edit the copy, and build a new stack with it.
- How do you insert an object safely when two Core Data models in one process both map to Plant?Avoid `Plant(context:)`, which has to guess the entity. Take the entity from the target context's model, `context.persistentStoreCoordinator?.managedObjectModel.entitiesByName["Plant"]`, and call `Plant(entity:insertInto:)`, or use `NSEntityDescription.insertNewObject(forEntityName:into:)`.
- Leaving an attribute's type undefined for a stored attribute
- Assuming isOptional defaults to false in a code-built model
- Building a fresh model in every test's setUp
- Mutating the model after the container has loaded its stores
- Forgetting managedObjectClassName and getting plain NSManagedObject instances