I have a viewController called 'MyViewController' in which I want to save some values to the user defaults. As key I wanted to use the class name "MyViewController" and append some string. Is it possible in Swift to get the String out of a class name? Thanks for any help :)
2 Answers
There may be a better way to do this, but as far as I know, you can get at the class name via classForCoder() (NSObject subclasses only). From there, you can use NSStringFromClass to convert the class name to an NSString. Only problem is the the name will often come out mangled, maybe "__lldb_expr_690.MyViewController". You can get around this by explicitly setting the name, ex:
@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" } } 2 Comments
borchero
Thanks for your answer, this is the only one working although this is a duplicate. The answers from the other question do not work at all.
prabhu
@borchero check this stackoverflow.com/a/47468006/2287422 its more simpler.
class MyOwnClass { } var myVar1 = NSString() var myVar2 = MyOwnClass() println(_stdlib_getTypeName(myVar1)) // Gives "NSString" println(_stdlib_getTypeName(myVar2)) // Gives "_TtC15__lldb_expr_26410MyOwnClass" 1 Comment
borchero
Actually it doesn't matter what's in front of the name but
_TtC15_lldb_expr_26410 changes when I start the program another time does it? Would be great if it wouldn't ^^