skip to content

In Core Data's model editor, what do the Class Definition, Category/Extension and Manual/None codegen settings generate for an entity, and when do you pick each?

level: juniorimportance: must knowfreq 66%

answer

  1. who owns the class source file
  2. generated files never enter your project
  3. +CoreDataClass and +CoreDataProperties
  4. one setting leaves only the class to you
  5. invalid redeclaration when both exist

basics

~10 s

Class Definition generates the NSManagedObject subclass and its @NSManaged properties at build time; Category/Extension generates only the properties extension and you write the class; Manual/None generates nothing, so you own both files.

solid answer

~40 s

Each entity names a class and a **Codegen** setting that decides who writes its Swift source. **Class Definition**, the default for new entities, regenerates `Plant+CoreDataClass.swift` and `Plant+CoreDataProperties.swift` on every build, outside your project; you add behaviour in extensions. **Category/Extension** regenerates only the properties extension, so you write `@objc(Plant) class Plant: NSManagedObject` yourself and can give it stored helpers or `final`. **Manual/None** generates nothing: you write the subclass and its `@NSManaged` properties, or create them once with Editor > Create NSManagedObject Subclass, and keep them in step with the model by hand. Pick Manual/None when you want property types the generator will not emit, such as a non-optional `String`. Mixing a hand-written class with Class Definition fails with "invalid redeclaration of 'Plant'".

code

swift · 22 lines
swift
import CoreData

// Plant.swift: yours to write when the entity's Codegen is Category/Extension.
@objc(Plant)
public class Plant: NSManagedObject {
    public var isDueForWater: Bool {
        guard let lastWatered else { return true }
        let next = Calendar.current.date(byAdding: .day, value: Int(wateringInterval), to: lastWatered)
        return next.map { $0 <= .now } ?? true
    }
}

// Plant+CoreDataProperties.swift: Xcode generates this half (abridged).
extension Plant {
    @nonobjc public class func fetchRequest() -> NSFetchRequest<Plant> {
        NSFetchRequest<Plant>(entityName: "Plant")
    }
    @NSManaged public var nickname: String?
    @NSManaged public var speciesName: String?
    @NSManaged public var wateringInterval: Int16
    @NSManaged public var lastWatered: Date?
}

go deeper

for a junior

Name the three settings and say which files each one generates. Know that generated files are rebuilt every time and are not yours to edit.

for a middle

Explain what @NSManaged means and why the generated class carries @objc(Plant). Show that extensions cover behaviour, so switching settings needs a better reason.

for a senior

Diagnose the invalid redeclaration and stale-file failures quickly, and pick the setting from what the class declaration must hold, not from habit.

for a principal

Weigh a team-wide rule: generated classes keep the model as the single truth, while manual classes buy precise Swift types at the cost of review effort on every model change.

## What the Codegen setting decides In a `.xcdatamodeld` file every **entity** (a record type, such as `Plant`) names the class that represents its objects at runtime: the **Class** field in the Data Model Inspector, `managedObjectClassName` on an `NSEntityDescription` in code. If no class is named, Core Data uses plain `NSManagedObject`. The **Codegen** setting beside it decides who writes the Swift source for that class. Core Data itself only needs a class with the right runtime name to exist; codegen is an Xcode build step that saves you typing it. The three settings differ in what Xcode writes and what is left to you: | Setting | Xcode generates | You write | Fits | |---|---|---|---| | **Class Definition** | `Plant+CoreDataClass.swift` and `Plant+CoreDataProperties.swift`, every build | nothing; behaviour goes in extensions | simple entities, the default for new ones | | **Category/Extension** | `Plant+CoreDataProperties.swift` only | the `Plant` class declaration | entities whose class you want in your sources | | **Manual/None** | nothing | the class and every `@NSManaged` property | full control over property types | ## What the generated code contains The generated files sit in the build's derived sources, not in your project, and are marked as not to be edited because the next build overwrites them. They contain: - an `@objc(Plant)` attribute on the class, so its Objective-C runtime name is `Plant` with no module prefix and matches the class the entity names; - `@nonobjc public class func fetchRequest() -> NSFetchRequest<Plant>`, a typed fetch request for the entity; - one `@NSManaged` property per attribute. **`@NSManaged`** tells the compiler that the property has no storage and no initial value in Swift: Core Data supplies the getter and setter at runtime and keeps the value in the managed object's own storage; - property types chosen from the attribute type and its **Use Scalar Type** box (the subject of the lesson on attribute types and optionality), not from the attribute's Optional box. ## Choosing a setting 1. **Start with Class Definition.** Computed properties, methods, protocol conformances and even overrides of Objective-C methods such as `awakeFromInsert()` can live in an extension of the generated class, so behaviour alone is not a reason to switch. 2. **Move to Category/Extension** when the class declaration itself must be yours: a stored property that is not part of the model (a cached formatter), the `final` keyword, documentation on the type, or a custom initializer. Xcode still keeps the attribute list in step with the model. 3. **Choose Manual/None** when the generated property types are wrong for you: a non-optional `speciesName: String` for an attribute that is never nil after save, a property with hand-written accessors, or an attribute you expose through a computed enum. The price is that every model change must be mirrored by hand. For the plant-care app, `Plant` gains an `isDueForWater` computed property and a cached date formatter. The computed property fits any setting; the stored formatter needs the class declaration, so the team picks Category/Extension. ## Failures that come from the setting - **"invalid redeclaration of 'Plant'"**: the entity is still on Class Definition while a `Plant.swift` declares the class too, often a leftover from Editor > Create NSManagedObject Subclass. Delete one or switch the setting. - **Stale manual files**: changing the setting does not delete files you generated earlier; an old properties file plus a newly generated one declares every property twice. - **Drift under Manual/None**: an attribute added in the editor has no property until you write it, and a property whose name matches no attribute fails at runtime when it is used. - **Wrong runtime name**: a hand-written class without `@objc(Plant)` gets a module-qualified runtime name, so the entity's Class field must name the module (the inspector's Module setting) or Core Data cannot find the class. ## What codegen does not change The setting is purely about Swift source. It does not affect: - **the store schema**: switching from Class Definition to Manual/None needs no migration, because codegen is not part of the schema the store records; - **validation**: the attribute's Optional box is still checked at save whatever the generated property says; - **runtime behaviour**: a hand-written `@NSManaged` property and a generated one are the same thing to Core Data, as long as the name and type match the attribute. That is why teams can change the setting entity by entity as the code grows, without touching existing users' data. ## Where it sits Codegen is the Core Data half of a choice SwiftData answers differently: there a `@Model` class is the schema, so there is no model file to generate from. In Core Data the model file stays the source of truth, and the codegen setting only decides how much of its Swift mirror Xcode writes for you.

  • Why does a generated Core Data class carry @objc(Plant) instead of relying on the Swift name?
    Core Data finds the class by the name the entity stores. A Swift class's runtime name normally includes its module, such as `PlantCare.Plant`; `@objc(Plant)` fixes the Objective-C name to `Plant`, so the lookup works whatever module the code is built into.
  • Can you override awakeFromInsert() if the entity uses Class Definition codegen?
    Yes. `awakeFromInsert()` is an Objective-C method of `NSManagedObject`, and Swift lets an extension override it, so an extension of the generated class can set a creation date there. What an extension cannot add is a stored property, which is one reason to move to Category/Extension.
  • What does Editor > Create NSManagedObject Subclass do, and when does it cause a build failure?
    It writes the class and properties files into your project once, as a starting point for Manual/None. If the entity is left on Class Definition, Xcode also generates its own copies, and the build fails with an invalid redeclaration of the class.

  • Editing Plant+CoreDataProperties.swift directly under Class Definition and expecting the change to survive
  • Saying Category/Extension is needed just to add a computed property or a method
  • Believing codegen changes how Core Data stores the data rather than who writes the Swift source
  • Keeping a hand-written Plant.swift while the entity stays on Class Definition
  • Thinking Manual/None keeps properties in sync with the model automatically