Swift ViewController class name as String

I have a viewController called MyViewController in which I want to store some values ​​for custom defaults. As a key, I wanted to use the class name "MyViewController" and add some line. Is it possible in Swift to infer String from class name? Thanks for any help :)

+3


source to share


2 answers


There is probably a better way to do this, but as far as I know you can get the class name via classForCoder () (NSObject subclasses only). From there, you can use NSStringFromClass to convert the class name to NSString. The only problem is that the name is often rendered crippled, possibly "__lldb_expr_690.MyViewController". You can work around this by explicitly specifying the name, for example:



@objc(MyViewController) class MyViewController: UIViewController {
    func aMethod() {
        let defaults = NSUserDefaults.standardUserDefaults()

        defaults.setObject("Some Object", forKey: NSStringFromClass(self.classForCoder))
        defaults.synchronize()
        // Has set "Some Object" for key "MyViewController"
    }
}

      

+3


source


class MyOwnClass {    
}

var myVar1 = NSString()
var myVar2 = MyOwnClass()

println(_stdlib_getTypeName(myVar1))    // Gives "NSString"
println(_stdlib_getTypeName(myVar2))    // Gives "_TtC15__lldb_expr_26410MyOwnClass"

      



0


source







All Articles