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.