【问题标题】:Can you get the name of the subclass calling a super method?你能得到调用超级方法的子类的名称吗?
【发布时间】:2015-12-01 06:15:37
【问题描述】:

我通常将create...:inContext: 方法添加到我的NSManagedObject 子类中,该方法插入然后初始化对象。所以,例如:

class Example : NSManagedObject {
    class func createWithArgument(arg: Int, inContext context: NSManagedObjectContext) -> Example {
        let example = NSEntityDescription.insertNewObjectForEntityForName("Example", inManagedObjectContext: context) as! Example

       // ...
    }
}

这适用于特定的类,但如果Example 是一个抽象模型,那么硬编码"Example" 将不起作用。我想要做的是插入调用createWithArgument:inContext: 方法的实体的类型,这样我就可以做这样的事情:

class SpecificExample : Example {
    class func createInContext(context: NSManagedObjectContext) -> SpecificExample {
        return super.createWithArgument(2, inContext: context)  // always 2 because reasons
    }
}

我最初的计划是获取调用类型的名称并将其用作实体名称(前提条件是类和实体名称始终匹配)。

不幸的是,这似乎不起作用;正如你所看到的,你总是得到父类型,即使你在子类上调用方法:

import UIKit

class Parent {
    class func getClassName(type: Any? = nil) -> String {
        return _stdlib_getDemangledTypeName(type ?? self).componentsSeparatedByString(".").first!
    }
}

class FirstChild : Parent {

}

class SecondChild : Parent {
    override class func getClassName(type: Any? = nil) -> String {
        return super.getClassName(self)
    }
}


Parent.getClassName() // Parent
FirstChild.getClassName() // Parent
SecondChild.getClassName() // SecondChild

现在,在我的具体示例中,还有其他方法可以实现相同的结果(例如,在子类中创建对象,然后调用继承的 init 方法)。

但是,我现在很好奇这种内省在 Swift 中是否完全可行。有没有办法做到这一点?

【问题讨论】:

  • 在面向对象编程中,任何时候你认为你需要知道一个类的name,你可能应该再想一想。整个概念是一种“难闻的气味”。
  • @matt 绝对同意,但是CoreData需要知道实体的名称(作为字符串)才能将其插入数据库,所以这有点特殊。

标签: swift introspection


【解决方案1】:

我不太明白你为什么不使用NSStringFromClass()

class Parent {
    class func whoami() -> String {
        return NSStringFromClass(self)
    }
}
class FirstChild : Parent {
}
class SecondChild : Parent {
}

还有一个纯 Swift 等价物,String()(或 Swift 1.2 及之前版本中的 toString()):

class Parent {
    class func whoami() -> String {
        return String(self)
    }
}
class FirstChild : Parent {
}
class SecondChild : Parent {
}

【讨论】:

  • 谢谢,这行得通。知道为什么 NSStringFromClass_stdlib_getDemangledTypeName 不适用的地方工作吗?
猜你喜欢
  • 2013-05-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-18
  • 2017-04-10
  • 1970-01-01
相关资源
最近更新 更多