TpoM6oH
TpoM6oH

Reputation: 8585

Dynamically instanciating ObjC class in Swift (with NSClassFromString?)

I have an ObjC class with an init method

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

In ObjC I dynamically create it with the following code:

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

But how would I do the same in Swift?

Upvotes: 1

Views: 308

Answers (1)

Kamil.S
Kamil.S

Reputation: 5543

Try this:

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))
}

More examples with details in my answer here

Upvotes: 3

Related Questions