获取对象的类名为String,使用:
object_getClassName(myViewController)
返回如下内容:
_TtC5AppName22CalendarViewController
我正在寻找纯粹的版本:“CalendarViewController”。我如何得到一个清理类名字符串代替?
我发现了一些关于这个问题的尝试,但没有一个实际的答案。难道根本不可能吗?
获取对象的类名为String,使用:
object_getClassName(myViewController)
返回如下内容:
_TtC5AppName22CalendarViewController
我正在寻找纯粹的版本:“CalendarViewController”。我如何得到一个清理类名字符串代替?
我发现了一些关于这个问题的尝试,但没有一个实际的答案。难道根本不可能吗?
当前回答
在Swift 4.1和现在的Swift 4.2中:
import Foundation
class SomeClass {
class InnerClass {
let foo: Int
init(foo: Int) {
self.foo = foo
}
}
let foo: Int
init(foo: Int) {
self.foo = foo
}
}
class AnotherClass : NSObject {
let foo: Int
init(foo: Int) {
self.foo = foo
super.init()
}
}
struct SomeStruct {
let bar: Int
init(bar: Int) {
self.bar = bar
}
}
let c = SomeClass(foo: 42)
let s = SomeStruct(bar: 1337)
let i = SomeClass.InnerClass(foo: 2018)
let a = AnotherClass(foo: 1<<8)
如果你周围没有实例:
String(describing: SomeClass.self) // Result: SomeClass
String(describing: SomeStruct.self) // Result: SomeStruct
String(describing: SomeClass.InnerClass.self) // Result: InnerClass
String(describing: AnotherClass.self) // Result: AnotherClass
如果你有一个实例:
String(describing: type(of: c)) // Result: SomeClass
String(describing: type(of: s)) // Result: SomeStruct
String(describing: type(of: i)) // Result: InnerClass
String(describing: type(of: a)) // Result: AnotherClass
其他回答
如果你不喜欢这个乱七八糟的名字,你可以口述你自己的名字:
@objc(CalendarViewController) class CalendarViewController : UIViewController {
// ...
}
然而,从长远来看,最好是学会解析这个混乱的名称。格式是标准的、有意义的,不会改变。
更新到swift 5
我们可以通过String初始化器使用实例变量获得类型名的详细描述,并创建某个类的新对象
例如,print(String(description: type(of: object)))。其中object可以是一个实例变量,如数组,字典,Int, NSDate等。
因为NSObject是大多数Objective-C类层次结构的根类,你可以尝试为NSObject做一个扩展,以获得NSObject的每个子类的类名。是这样的:
extension NSObject {
var theClassName: String {
return NSStringFromClass(type(of: self))
}
}
或者您可以创建一个静态函数,其参数类型为Any(所有类型隐式遵循的协议),并将类名返回为String。是这样的:
class Utility{
class func classNameAsString(_ obj: Any) -> String {
//prints more readable results for dictionaries, arrays, Int, etc
return String(describing: type(of: obj))
}
}
现在你可以这样做:
class ClassOne : UIViewController{ /* some code here */ }
class ClassTwo : ClassOne{ /* some code here */ }
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Get the class name as String
let dictionary: [String: CGFloat] = [:]
let array: [Int] = []
let int = 9
let numFloat: CGFloat = 3.0
let numDouble: Double = 1.0
let classOne = ClassOne()
let classTwo: ClassTwo? = ClassTwo()
let now = NSDate()
let lbl = UILabel()
print("dictionary: [String: CGFloat] = [:] -> \(Utility.classNameAsString(dictionary))")
print("array: [Int] = [] -> \(Utility.classNameAsString(array))")
print("int = 9 -> \(Utility.classNameAsString(int))")
print("numFloat: CGFloat = 3.0 -> \(Utility.classNameAsString(numFloat))")
print("numDouble: Double = 1.0 -> \(Utility.classNameAsString(numDouble))")
print("classOne = ClassOne() -> \((ClassOne).self)") //we use the Extension
if classTwo != nil {
print("classTwo: ClassTwo? = ClassTwo() -> \(Utility.classNameAsString(classTwo!))") //now we can use a Forced-Value Expression and unwrap the value
}
print("now = Date() -> \(Utility.classNameAsString(now))")
print("lbl = UILabel() -> \(String(describing: type(of: lbl)))") // we use the String initializer directly
}
}
而且,一旦我们可以获得类名String,我们就可以实例化该类的新对象:
// Instantiate a class from a String
print("\nInstantiate a class from a String")
let aClassName = classOne.theClassName
let aClassType = NSClassFromString(aClassName) as! NSObject.Type
let instance = aClassType.init() // we create a new object
print(String(cString: class_getName(type(of: instance))))
print(instance.self is ClassOne)
也许这能帮助一些人!
在我的例子中,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也可以。上面的函数也是故障安全的:)
有时其他解决方案会给出一个无用的名称,这取决于您试图查看的对象。在这种情况下,您可以使用以下命令获取类名作为字符串。
String(cString: object_getClassName(Any!))
⌘单击xcode中的函数,查看一些相当有用的相关方法。或者点击这里查看https://developer.apple.com/reference/objectivec/objective_c_functions
要在Swift 4中获得类型名为字符串(我没有检查早期版本),只需使用字符串插值:
"\(type(of: myViewController))"
你可以在类型本身上使用.self,在实例上使用type(of:_)函数:
// Both constants will have "UIViewController" as their value
let stringFromType = "\(UIViewController.self)"
let stringFromInstance = "\(type(of: UIViewController()))"