Home » Swift » NSClassFromString() always returns nil

NSClassFromString() always returns nil

Posted by: admin November 30, 2017 Leave a comment

Questions:

The following code prints nil, despite ListCell is a valid class.

var lCellClass : AnyClass! = NSClassFromString("ListCell");

println(lCellClass);

The docs are saying that method returns

The class object named by aClassName, or nil if no class by that name is currently loaded. If aClassName is nil, returns nil.

I also tried to get NSClassFromString() of current viewcontroller which is LOADED but still get nil

What can be the problem ?

Update:
Even trying to do this NSClassFromString("Array") I still get nil

Answers:

The NSClassFromString function does work for (pure and Objective-C-derived) swift classes, but only if you use the fully qualified name.

For example, in a project called MyApp with a pure swift class called Person:

let personClass: AnyClass? = NSClassFromString("MyApp.Person")

See Using Swift Class Names with Objective-C APIs in Using Swift With Cocoa and Objective-C for more information.

Questions:
Answers:

It’s also possible to specify a name for the symbol in Objective-C which omits the namespace in objective C by using the @objc annotation. If you prefer to use the name without the module, just use the same class name:

@objc(Foobar)
class Foobar{

}

NSClassFromString(“Foobar”) will return the class Foobar.

Questions:
Answers:

This may be problem that your class have not extend from NSObject. As by default swift does not have superclass.