获取对象的类名为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
其他回答
Swift 5.1:-
你也可以使用泛型函数获取对象的类名作为字符串
struct GenericFunctions {
static func className<T>(_ name: T) -> String {
return "\(name)"
}
}
使用以下方法调用此函数:-
let name = GenericFunctions.className(ViewController.self)
快乐编码:)
我一直在断断续续地寻找这个答案。我使用GKStateMachine,喜欢观察状态变化,想要一种简单的方法来查看类名。我不确定它是iOS 10还是Swift 2.3,但在这种环境下,以下内容正是我想要的:
let state:GKState?
print("Class Name: \(String(state.classForCoder)")
// Output:
// Class Name: GKState
你可以通过如下方式获取类名:
class Person {}
String(describing: Person.self)
斯威夫特5.2:
String(describing: type(of: self))
有时其他解决方案会给出一个无用的名称,这取决于您试图查看的对象。在这种情况下,您可以使用以下命令获取类名作为字符串。
String(cString: object_getClassName(Any!))
⌘单击xcode中的函数,查看一些相当有用的相关方法。或者点击这里查看https://developer.apple.com/reference/objectivec/objective_c_functions