Reputation: 2410
I'm trying to dynamically load a Swift class inheriting from NSObject
using the objc runtime. (I'm trying to load the class from ObjC, not from Swift)
My Swift class:
@objc public class TestClass : NSObject {
@objc public func testMethod() -> String {
return "String"
}
}
According to Apple's documentation,
The
@objc
attribute makes your Swift API available in Objective-C and the Objective-C runtime
But the result of objc_getClass("TestClass")
is (null)
.
Am I doing something wrong? Or is it not possible at all to load swift classes inheriting an ObjC class using the objc runtime?
Upvotes: 2
Views: 1494
Reputation: 42449
You need to specify an Objective-C name for your class, not just include @objc
:
@objc(TestClass) public class TestClass : NSObject {
@objc public func testMethod() -> String {
return "String"
}
}
NSClassFromString("TestClass") // TestClass.Type
objc_getClass("TestClass") // TestClass
Otherwise your class will not be registered with the Objective-C runtime, and calls like objc_getClass
or NSClassFromString
will return nil
.
Upvotes: 4
Reputation: 21808
What if you try objc_getClass("YourAppName.TestClass")
? Most likely the module name is prepended. You can verify the exact name which is used behind the scenes by using NSStringFromClass([TestClass class])
Upvotes: 2