一尘不染

Swift语言NSClassFromString

swift

如何在Swift语言中实现反射

如何实例化课程

[[NSClassFromString(@"Foo") alloc] init];

阅读 330

收藏
2020-07-07

共1个答案

一尘不染

请注意,Swift类现在已命名为名称空间,因此它将是“ AppName.MyViewController”而不是“ MyViewController”


从XCode6-beta 6/7开始不推荐使用

使用XCode6-beta 3开发的解决方案

多亏了Edwin Vermeer的回答,我能够通过执行以下操作来构建一些东西来将Swift类实例化为Obj-C类:

// swift file
// extend the NSObject class
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  var 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 = "_TtC\(appName!.utf16count)\(appName)\(countElements(className))\(className)"
            // return the class!
            return NSClassFromString(classStringName)
        }
        return nil;
    }
}

// obj-c file
#import "YourProject-Swift.h"

- (void)aMethod {
    Class class = NSClassFromString(key);
    if (!class)
        class = [NSObject swiftClassFromString:(key)];
    // do something with the class
}

编辑

您也可以在纯obj-c中执行此操作:

- (Class)swiftClassFromString:(NSString *)className {
    NSString *appName = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleName"];
    NSString *classStringName = [NSString stringWithFormat:@"_TtC%d%@%d%@", appName.length, appName, className.length, className];
    return NSClassFromString(classStringName);
}

我希望这会对某人有所帮助!

2020-07-07