0

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.

Peppo
  • 1,107
  • 1
  • 12
  • 19
Pieter
  • 2,621
  • 4
  • 19
  • 26
  • Did you check all answers from http://stackoverflow.com/questions/24030814/swift-language-nsclassfromstring ? This one looks close to what you want: http://stackoverflow.com/a/32265287/1187415. – Martin R Dec 28 '15 at 11:06
  • See the edit in my post... – Pieter Dec 28 '15 at 16:03

1 Answers1

0

Try the code given below

let viewController = storyboard?.instantiateViewControllerWithIdentifier("ViewController") as! ViewController

This code allow you to instantiate the storyboard view controller. But you can not pass the View Controller class name.

You have to pass the storyboard identifier of the view controller. Please review the below picture for it.

enter image description here

luk2302
  • 55,258
  • 23
  • 97
  • 137