4

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 :)

0

2 Answers 2

4

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" } } 
Sign up to request clarification or add additional context in comments.

2 Comments

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.
@borchero check this stackoverflow.com/a/47468006/2287422 its more simpler.
0
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

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 ^^

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.