简体   繁体   中英

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.

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.

There is nothing wrong in doing this:

class Instrument: NSManagedObject {
  @NSManaged var name: String
}

class Guitar: Instrument {
  @NSManaged var numberOfString: NSNumber
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM