Search code examples
iosswiftnsuserdefaults

Swift NSUserDefaults setString:forKey:?


NSUserDefaults has integerForKey:, setInteger:forKey: and stringForKey:, but does not have setString:forKey:.

How do you set a string to NSUserDefaults? It has setObject:forKey: but, in Swift, String is a struct. Is it ok to use setObject:forKey: to store a string?


Solution

  • The reason that setObject can be used to apply a string is found in the discussion of the reference:

    discussion

    Since Swift String is bridged to NSString, the usage of setObject is valid. However as the other types mentioned are not accepted in NSUserDefaults using the setObject setter; they have their own convenience setters.

    convenience-inits

    Notwithstanding this, almost anything one can think of can be serialized and placed into NSUserDefaults using setObject with an NSData argument (as noted elsewhere on SO).