Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 830
ahoang Avatar asked Feb 24 '15 21:02

ahoang


1 Answers

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.

like image 115
Osmund Avatar answered Nov 20 '22 05:11

Osmund