the Reverend
the Reverend

Reputation: 12549

Get ClassName without referencing self

I want to initialize a UIViewController subclass with a default nib name. The only way I can think is to get the current class name. But to do it, I need to reference self, and it is not possible before calling super.initWithNib.

    init(managedObject: NSManagedObject){
        let className = PSOClassNameFor(self) /// ERROR -> Cannot reference self

        self.managedObject = managedObject
        super.init(nibName:className, bundle: nil)
    }

I don't know the actual name for the class, since this is an abstract class with multiple subclasses.

Any other way to load a default nibName?

These are the two files in play:

enter image description here

When I try to initialize with a nil nibName it load a black screen.

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

When I specify the nib name it works as expected:

    init(){
    super.init(nibName: "EntityCardViewController", bundle: nil)
}

Upvotes: 0

Views: 620

Answers (2)

clreina
clreina

Reputation: 41

For Swift 3:

    init() {
        super.init(nibName: String(describing: type(of: self)), bundle: nil)
    }

Upvotes: 2

BaseZen
BaseZen

Reputation: 8718

Maybe I'm missing something obvious, but this just worked fine in Xcode 6.4/Swift 1.2:

import CoreData
class MySubVC: UITableViewController {
    init(managedObject: NSManagedObject){
        let className = self.dynamicType.description()
        println(className) // Project_Name.MySubVC; not so bad; easily parsed
        super.init(nibName: className, bundle: nil)
    }

    required init!(coder aDecoder: NSCoder!) {
        super.init(coder: aDecoder)
    }
}

Upvotes: 1

Related Questions