获取对象的类名为String,使用:

object_getClassName(myViewController)

返回如下内容:

_TtC5AppName22CalendarViewController

我正在寻找纯粹的版本:“CalendarViewController”。我如何得到一个清理类名字符串代替?

我发现了一些关于这个问题的尝试,但没有一个实际的答案。难道根本不可能吗?


当前回答

要获得类名为String,请按以下方式声明类

@objc(YourClassName) class YourClassName{}

并使用以下语法获取类名

NSStringFromClass(YourClassName)

其他回答

你可以试试这种方法:

self.classForCoder.description()

如果你不喜欢这个乱七八糟的名字,你可以口述你自己的名字:

@objc(CalendarViewController) class CalendarViewController : UIViewController {
    // ...
}

然而,从长远来看,最好是学会解析这个混乱的名称。格式是标准的、有意义的,不会改变。

要从对象中获取Swift类的名称,例如var object: SomeClass(),使用

String(describing: type(of: object))

要从类类型中获取Swift类的名称,例如SomeClass,使用:

String(describing: SomeClass.self)

输出:

" SomeClass "

在我的例子中,String(description: self)返回如下内容:

< My_project。ExampleViewController: 0x10b2bb2b0 >

但我想在Android上有类似getSimpleName的东西。

所以我创建了一个小扩展:

extension UIViewController {

    func getSimpleClassName() -> String {
        let describing = String(describing: self)
        if let dotIndex = describing.index(of: "."), let commaIndex = describing.index(of: ":") {
            let afterDotIndex = describing.index(after: dotIndex)
            if(afterDotIndex < commaIndex) {
                return String(describing[afterDotIndex ..< commaIndex])
            }
        }
        return describing
    }

}

现在它返回:

ExampleViewController

扩展NSObject而不是UIViewController也可以。上面的函数也是故障安全的:)

如果你的类型是Foo,下面的代码会在Swift 3和Swift 4中给你“Foo”:

let className = String(describing: Foo.self) // Gives you "Foo"

这里大多数答案的问题是,他们给你“Foo”。当你没有该类型的任何实例时,当你真正想要的只是"Foo"时,输入"作为结果字符串。下面是“Foo”。输入“”,就像在其他答案中提到的那样。

let className = String(describing: type(of: Foo.self)) // Gives you "Foo.Type"

如果您只想要“Foo”,则不需要使用类型(of:)部分。