zoukankan      html  css  js  c++  java
  • [swift] NSClassFromString 无法获得该类

    在写OC的时候需要用 NSClassFromString(classStringName)获得一个类,如果存在就用这个类型来声明一个对象,

    但是在swift的时候却往往得不到这个类,为什么呢?

    从截图看

    分析swift里面的对象还有该工程的名字CFBundleName

    所以我们可以分析出只要加上该工程的名字就可以得到这个类了写法如下

    extension NSObject {
        // create a static method to get a swift class for a string name
        class func swiftClassFromString(className: String) -> AnyClass! {
            // get the project name
            if  let appName: String? = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleName") as! String? {
                // generate the full name of your class (take a look into your "YourProject-swift.h" file)
                let classStringName = appName! + "." + className
                // return the class!
                return NSClassFromString(classStringName)
            }
            return nil;
        }
    }

    而如果不想这样做呢

    还有一种方法

    就是在该类声明的时候加上@objc修饰符

    置于为什么需要objc,参考前一篇《Swift与Objective-C的兼容“黑魔法”:@objc和Dynamic

  • 相关阅读:
    PHP—字符串编码
    使用html模板
    创建html模板
    默认.htpl改为.htpl
    eclipse导入项目前面有感叹号
    eclipse点不出方法
    eclipse界面混乱
    面试题
    多线程
    瀑布流
  • 原文地址:https://www.cnblogs.com/nonato/p/4870817.html
Copyright © 2011-2022 走看看