Swift语言NSClassFromString [英] Swift language 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屋!