如何将具有类名称的字符串转换为类类型本身? [英] How to convert a string with the name of a class to the class type itself?

查看:91
本文介绍了如何将具有类名称的字符串转换为类类型本身?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了在日志文件中存储类名,我将类类型的描述转换为字符串:

  let objectType:NSObject.Type = Object.self 
let str = String(描述:objectType)



<但是,我没有成功地将 str 转换为 NSObject.Type 类型的变量来使用它在一个通用的方法中。



我怎么能做到这一点?

解决方案

您可以从 string 返回类,但在获取类名时需要使用项目的 module 名称。如果您没有使用模块名称,那么它将返回 nil ,因为您之前引用的类名称未由模块名称完全限定。您应该更改类名称字符串以表示您的类的完全限定名称:

  let myClassString = String(MyModule.MyViewController。 self)
print(myClassString)
let myClass = NSClassFromString(MyModule.\(myClassString))as! MyViewController.Type
print(myClass)


In order to store a class name in a log file I converted the description of a class type to a string:

let objectType: NSObject.Type = Object.self
let str = String(describing: objectType)

However, I do not succeed in back conversion of str to a variable of type NSObject.Type to use it in a generic method.

How could I do this?

解决方案

You can get your class back from string, but you need to use your project's module name while getting class name. If you don't use your module name then it will return nil because the class name you have referenced earlier is not fully qualified by the module name. You should change the class name string to represent the fully qualified name of your class:

let myClassString = String(MyModule.MyViewController.self)
print(myClassString)
let myClass = NSClassFromString("MyModule.\(myClassString)") as! MyViewController.Type
print(myClass)

这篇关于如何将具有类名称的字符串转换为类类型本身?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆