在 Swift 中动态实例化 ObjC class(使用 NSClassFromString?)

Dynamically instanciating ObjC class in Swift (with NSClassFromString?)

我有一个带有 init 方法的 ObjC class

-(instancetype) initWithApiKey: (NSString *) key order: (NSNumber *) order

在 ObjC 中,我使用以下代码动态创建它:

id classAllocation = [NSClassFromString(@"MyClass") alloc];
NSObject * classInstance = [classAllocation performSelector:@selector(initWithApiKey:order:) 
withObject:@"mykey" withObject:@1];

但是我如何在 Swift 中做同样的事情?

试试这个:

if let allocatedObject = NSClassFromString("MyClass")?.alloc() as? NSObject {
    let selector: Selector = NSSelectorFromString("initWithApiKey:order:")
    let methodIMP: IMP! = allocatedObject.method(for: selector)
    let objectAfterInit = unsafeBitCast(methodIMP,to:(@convention(c)(AnyObject?,Selector,NSString,NSNumber)->NSObject).self)(allocatedObject,selector,"mykey", NSNumber(integerLiteral: 1))
}

我的回答中有更多示例和详细信息here