【问题标题】:Swift how to create class instance from string originating in libSwift如何从源自lib的字符串创建类实例
【发布时间】:2019-10-29 16:26:23
【问题描述】:

我正在尝试从对其类名的字符串引用创建一个 swift 类

我可以得到一个类型,但是我不知道如何从 AnyClass 到一个初始化的实例

let className: String = "myLibDomain.className"
if let referencedClass = NSClassFromString(className){
    if let conformantReferanceClass = referencedClass as? myProtocol {
        //do some work defined by myProtocol
    }
}

NSClassFromSting 给我返回了 AnyClass 类型的东西,在调试器中它看起来像这样: myLibDomain.className 它没有分配内存,我相信我错过了一步。 AnyClass 没有 init() 方法

【问题讨论】:

    标签: ios swift xcode


    【解决方案1】:

    我可以通过将第 2 行修改为如下所示来实现这一点:

    if let referencedClass = NSClassFromString(className)?.alloc()
    

    这看起来合理吗?我从未在 swift 中使用过该关键字,我正在寻找一些针对同一问题的客观 c 解决方案。注意:我正在使用的示例中的“referancedClass”不是从 NSObject 继承的

    【讨论】:

      猜你喜欢
      • 2017-03-15
      • 2020-07-30
      • 1970-01-01
      • 2015-07-22
      • 1970-01-01
      • 1970-01-01
      • 2015-11-23
      • 2011-04-14
      相关资源
      最近更新 更多