Search code examples
iosswiftcore-datansmanagedobject

Subclass an NSManagedObject subclass


Let's say I have an NSManagedObject subclass Instrument and I want to subclass that subclass to create something like Guitar. Is there a common practice for this? It doesn't seem to be as straightforward as subclassing NSObject.


Solution

  • For managed object subclasses, the subclass/parent class relationship corresponds to the subentity/parent entity relationship of the Core Data entities.

    If you set the "Parent Entity" of "Guitar" to "Instrument" in the Core Data model inspector and then create the managed object subclasses in Xcode, you'll get

    // Instrument.swift:
    class Instrument: NSManagedObject {
    
    // Insert code here to add functionality to your managed object subclass
    
    }
    
    // Guitar.swift:
    class Guitar: Instrument {
    
    // Insert code here to add functionality to your managed object subclass
    
    }
    

    For more information, see the section "Entity Inheritance" in the Core Data Programming Guide:

    Entity inheritance works in a similar way to class inheritance, and is useful for the same reasons. If you have a number of entities that are similar, you can factor the common properties into a superentity, also known as a parent entity.

    Also pay attention to the

    NOTE

    Be careful with entity inheritance when working with SQLite persistent stores. All entities that inherit from another entity will exist within the same table in SQLite. This factor in the design of the SQLite persistent store can create a performance issue.