【问题标题】:How to call a static property within the initializer of a subclass in Swift? [duplicate]如何在 Swift 子类的初始化程序中调用静态属性? [复制]
【发布时间】:2018-07-08 12:45:36
【问题描述】:

我在NSManagedObject 上创建了一个扩展来返回一个实体名称,该名称等于对象的具体类名,可能是子类的名称:

extension NSManagedObject {

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

}

我希望这个属性为一个子类返回字符串“Coffee”,定义如下:

class Coffee: NSManagedObject { ... }

现在我还想在 NSManagedObject 上定义一个自定义初始化程序,它使用上面定义的属性 entityName

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)
    }

}

问题是我不知道如何访问这里的静态entityName。显然,我不能将其称为NSManagedObject.entityName,因为这将执行超类的实现,该实现将返回“NSManagedObject”而不是“Coffee”。 Self 也不起作用,因为它不是协议。

那么如何在这个初始化器中调用实际子类的静态属性呢?

【问题讨论】:

    标签: swift initialization subclass static-methods static-members


    【解决方案1】:

    您可以使用type(of: self),以便访问实体名称

    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)
        }
    
    }
    

    【讨论】:

    • 在初始化之前不能调用对象的实例属性。
    • 对不起,我错过了我正在更新我的答案
    • 谢谢,但更准确地说:在self 初始化之前,您无法访问self
    • 你可以在类型中使用
    • 天啊,我不知道!谢谢! (在我看来这有点不一致,但我很高兴它有效......?)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-28
    • 1970-01-01
    • 1970-01-01
    • 2014-11-22
    相关资源
    最近更新 更多