获取对象的类名为String,使用:
object_getClassName(myViewController)
返回如下内容:
_TtC5AppName22CalendarViewController
我正在寻找纯粹的版本:“CalendarViewController”。我如何得到一个清理类名字符串代替?
我发现了一些关于这个问题的尝试,但没有一个实际的答案。难道根本不可能吗?
获取对象的类名为String,使用:
object_getClassName(myViewController)
返回如下内容:
_TtC5AppName22CalendarViewController
我正在寻找纯粹的版本:“CalendarViewController”。我如何得到一个清理类名字符串代替?
我发现了一些关于这个问题的尝试,但没有一个实际的答案。难道根本不可能吗?
当前回答
我一直在断断续续地寻找这个答案。我使用GKStateMachine,喜欢观察状态变化,想要一种简单的方法来查看类名。我不确定它是iOS 10还是Swift 2.3,但在这种环境下,以下内容正是我想要的:
let state:GKState?
print("Class Name: \(String(state.classForCoder)")
// Output:
// Class Name: GKState
其他回答
如果你不喜欢这个乱七八糟的名字,你可以口述你自己的名字:
@objc(CalendarViewController) class CalendarViewController : UIViewController {
// ...
}
然而,从长远来看,最好是学会解析这个混乱的名称。格式是标准的、有意义的,不会改变。
有时其他解决方案会给出一个无用的名称,这取决于您试图查看的对象。在这种情况下,您可以使用以下命令获取类名作为字符串。
String(cString: object_getClassName(Any!))
⌘单击xcode中的函数,查看一些相当有用的相关方法。或者点击这里查看https://developer.apple.com/reference/objectivec/objective_c_functions
我试着用Swift 3在Playground中输入(…)这是我的结果。 这是代码格式版本。
print(String(describing: type(of: UIButton.self)))
print(String(describing: type(of: UIButton())))
UIButton.Type
UIButton
你可以试试这种方法:
self.classForCoder.description()
我建议这样的方法(非常Swifty):
// Swift 3
func typeName(_ some: Any) -> String {
return (some is Any.Type) ? "\(some)" : "\(type(of: some))"
}
// Swift 2
func typeName(some: Any) -> String {
return (some is Any.Type) ? "\(some)" : "\(some.dynamicType)"
}
它既不使用内省,也不使用手动提取(没有魔法!)
下面是一个演示:
// Swift 3
import class Foundation.NSObject
func typeName(_ some: Any) -> String {
return (some is Any.Type) ? "\(some)" : "\(type(of: some))"
}
class GenericClass<T> {
var x: T? = nil
}
protocol Proto1 {
func f(x: Int) -> Int
}
@objc(ObjCClass1)
class Class1: NSObject, Proto1 {
func f(x: Int) -> Int {
return x
}
}
struct Struct1 {
var x: Int
}
enum Enum1 {
case X
}
print(typeName(GenericClass<Int>.self)) // GenericClass<Int>
print(typeName(GenericClass<Int>())) // GenericClass<Int>
print(typeName(Proto1.self)) // Proto1
print(typeName(Class1.self)) // Class1
print(typeName(Class1())) // Class1
print(typeName(Class1().f)) // (Int) -> Int
print(typeName(Struct1.self)) // Struct1
print(typeName(Struct1(x: 1))) // Struct1
print(typeName(Enum1.self)) // Enum1
print(typeName(Enum1.X)) // Enum1