2

I have created an extension on NSManagedObject to return an entity name equal to the object's concrete class name, possibly the name of a subclass:

extension NSManagedObject {

    static var entityName: String {
        return String(describing: self)
    }

}

I expect that this property returns the string "Coffee" for a subclass defined as follows:

class Coffee: NSManagedObject { ... }

Now I also want to define a custom initializer on NSManagedObject which uses the property entityName defined above.

extension NSManagedObject {

    convenience init(context: NSManagedObjectContext) {
        let entityName = Self.entityName //  How to obtain the entity here?
        guard let entity = NSEntityDescription.entity(forEntityName: entityName, in: context) else {
            fatalError("Could not find entity with name \(entityName)")
        }
        self.init(entity: entity, insertInto: context)
    }

}

The problem is that I don't know how to access the static entityName here. Obviously, I cannot refer to it as NSManagedObject.entityName as this would execute the superclass' implementation which would return "NSManagedObject" rather than "Coffee". Self doesn't work either because it's not a protocol.

So how can I call the static property on the actual subclass from within this initializer?

Mischa
  • 15,816
  • 8
  • 59
  • 117

1 Answers1

1

You can use type(of: self) so you can access the entity name

extension NSManagedObject {

    convenience init(context: NSManagedObjectContext) {

        let entityName = type(of: self).entityName //  How to obtain the entity here?
        guard let entity = NSEntityDescription.entity(forEntityName: entityName, in: context) else {
            fatalError("Could not find entity with name \(entityName)")
        }
        self.init(entity: entity, insertInto: context)
    }

}
hardikdevios
  • 1,779
  • 14
  • 33