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

borchero
  • 5,562
  • 8
  • 46
  • 72

2 Answers2

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"
    }
}
Mick MacCallum
  • 129,200
  • 40
  • 280
  • 281
  • 1
    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 Jan 02 '15 at 17:15
  • 1
    @borchero check this https://stackoverflow.com/a/47468006/2287422 its more simpler. – prabhu Nov 24 '17 at 07:16
0
class MyOwnClass {    
}

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

println(_stdlib_getTypeName(myVar1))    // Gives "NSString"
println(_stdlib_getTypeName(myVar2))    // Gives "_TtC15__lldb_expr_26410MyOwnClass"
SrB
  • 353
  • 4
  • 11
  • 1
    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 ^^ – borchero Jan 02 '15 at 17:13