5

I am trying to create a Class like this :

class MyClass<T:UIView>: UIViewController{


    override init()
    {
        super.init(nibName: nil, bundle: nil);
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func loadView() {
        self.view = T();
        println("loadView")
    }

    override func viewDidLoad() {
        super.viewDidLoad();
        println("viewDidLoad")
    }

}

When I want to use my class like that :

self.navigationController?.pushViewController(MyClass<UIView>(), animated: true)

The methods viewDidLoad and loadView are never called !!!

Do you know why and if there is some way of doing what I want.

Thanks in advance.

Fred
  • 51
  • 1
  • 2

1 Answers1

5

As mentioned in OP comments, Generic class cannot be properly represented in Objective-C.

The workaround would be using the class as a property. something like this:

class MyClass: UIViewController{

    let viewCls:UIView.Type

    init(viewCls:UIView.Type = UIView.self) {
        self.viewCls = viewCls
        super.init(nibName: nil, bundle: nil);
    }

    required init(coder aDecoder: NSCoder) {
        self.viewCls = UIView.self
        super.init(coder: aDecoder)
    }

    override func loadView() {
        self.view = viewCls();
        println("loadView")
    }

    override func viewDidLoad() {
        super.viewDidLoad();
        println("viewDidLoad")
    }

}

// and then
self.navigationController?.pushViewController(MyClass(viewCls: UIView.self), animated: true)
rintaro
  • 51,423
  • 14
  • 131
  • 139