ahoang
ahoang

Reputation: 139

NSClassFromString using a Swift File

I have written a class in Swift in my existing Objective-C project. So far, the bridging has worked very well. I do have a method however, where I generate a class at runtime using NSClassFromString(). When the string is my Swift class name, it returns nil.

class MySwiftClass : NSObject {}

and in Objective-C:

Class myClass = NSClassFromString(@"MySwiftClass");

and myClass would be nil every time. I've also tried:

Class myClass = NSClassFromString(@"MyAppName.MySwiftClass");

and still nil.

Upvotes: 5

Views: 2888

Answers (2)

无夜之星辰
无夜之星辰

Reputation: 6198

A way to compatible Objective-C and Swift:

CQBaseViewController *detailVC = [[NSClassFromString(controller_name) alloc] init];

// if nil,check as Swift file
if (!detailVC) {
    NSString *prefix = [[NSBundle mainBundle] infoDictionary][@"CFBundleExecutable"];
    NSString *swiftClassName = [NSString stringWithFormat:@"%@.%@", prefix, controller_name];
    detailVC = [[NSClassFromString(swiftClassName) alloc] init];
}

Upvotes: 0

Osmund
Osmund

Reputation: 802

All swift classes use the Product Module Name a dot and the classname for their namespace (Module.Class). If you wanted to use "MySwiftClass" name for the class within your Objective-C code; you can add @objc(MySwiftClass) annotation to expose the same swift class name (without the module):

@objc(MySwiftClass)
class MySwiftClass{
    ...
}

Then

Class myClass = NSClassFromString(@"MySwiftClass");

Will contain the class instead of being nil.

Upvotes: 15

Related Questions