I guess I read most of the SO questions and Google answers on this, but still cannot get it working. Take this code example:
import UIKit
class Person: NSObject {
var name = "Pieter"
}
let PersonClass: AnyClass? = NSClassFromString("Person")
let person = PersonClass()
print(person.name)
Changing NSClassFromString("Person")
into NSClassFromString("MyAppName.Person")
does not make a difference. Adding as! NSObject.Type
behind the PersonClass declaration neither. Adding @obcj(Person
before the class declaration neither.
The real-life goal is to read class names from a database and load the appropriate storyboard / UIViewController accordingly. So I am looking for a way to pass the UIViewController class name as a String and instantiate the UIStoryboard with it.
How to do that?
Edit: here is what I currently try for the real-life scenario after your suggestions:
let storyboard = UIStoryboard(name: "MyStoryboard", bundle: nil)
let MyClassName = "MyApp.MyTableViewController"
let MyClass = NSClassFromString(MyClassName) as! UITableViewController.Type
let controller = storyboard.instantiateInitialViewController() as! MyClass
It gives an error saying "MyClass" is not a type
. I cannot remove it or I will get an error that it cannot convert from AnyClass
.