Swift 语言 NSClassFromString [英] Swift language NSClassFromString

查看:33
本文介绍了Swift 语言 NSClassFromString的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 Swift 语言中实现反射?

How to achieve reflection in Swift Language?

如何实例化一个类

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

推荐答案

这里有更简单的解决方案:https://stackoverflow.com/a/32265287/308315

Less hacky solution here: https://stackoverflow.com/a/32265287/308315

请注意,Swift 类现在是命名空间的,而不是MyViewController".它会是AppName.MyViewController"

Note that Swift classes are namespaced now so instead of "MyViewController" it'd be "AppName.MyViewController"

自 XCode6-beta 6/7 起弃用

Deprecated since XCode6-beta 6/7

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

Solution developed using XCode6-beta 3

感谢 Edwin Vermeer 的回答,我能够通过这样做来构建一些东西来将 Swift 类实例化为 Obj-C 类:

Thanks to the answer of Edwin Vermeer I was able to build something to instantiate Swift classes into an Obj-C class by doing this:

// 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 中实现:

You can also do it in pure 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);
}

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

I hope this will help somebody !

这篇关于Swift 语言 NSClassFromString的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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