21

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?

Yoichi Tagaya
  • 4,547
  • 2
  • 27
  • 38

4 Answers4

22

update: Xcode 13.2.1 • Swift 5.5.2

let string = "Hello World"

UserDefaults.standard.set(string, forKey: "string")

if let loadedString = UserDefaults.standard.string(forKey: "string") {
    print(loadedString) // "Hello World"
}

The nice thing about Swift is that it allows to you to easily extend the language. You can create your own date(forKey:) extending UserDefaults to create an instance method as follow:

extension UserDefaults {
    func date(forKey defaultName:String) -> Date? {
        object(forKey: defaultName) as? Date
    }
}

let userName = "Chris Lattner"
let userAddress = "1 Infinite Loop, Cupertino, CA 95014, United States"
let userDOB = DateComponents(calendar: .init(identifier: .gregorian), year: 1978).date!

UserDefaults.standard.set(userName, forKey: "userName")
UserDefaults.standard.set(userAddress, forKey: "userAddress")
UserDefaults.standard.set(userDOB, forKey: "userDOB")

let loadedUserName = UserDefaults.standard.string(forKey: "userName")
let loadedUserAddress = UserDefaults.standard.string(forKey: "userAddress")
let loadedUserDOB = UserDefaults.standard.date(forKey: "userDOB")

print(loadedUserName ?? "nil")    // "Chris Lattner"
print(loadedUserAddress ?? "nil") // "1 Infinite Loop, Cupertino, CA 95014, United States"
print(loadedUserDOB?.description(with: .init(identifier: "en_US")) ?? "nil")  // "Sunday, January 1, 1978 at 12:00:00
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
19

Swift 3 removed .setObject. Use .set instead. For example:

// Create UserDefaults
let defaults = UserDefaults.standard

// Save String value to UserDefaults
// Using defaults.set(value: Any?, forKey: String)
defaults.set("Some string you want to save", forKey: "savedString")

// Get the String from UserDefaults
if let myString = defaults.string(forKey: "savedString") {
    print("defaults savedString: \(myString)")
}
Daniel Storm
  • 18,301
  • 9
  • 84
  • 152
14

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

Dimitar Nestorov
  • 2,411
  • 24
  • 29
Tommie C.
  • 12,895
  • 5
  • 82
  • 100
  • Thank you for your answer. The other answers are exact and appreciated but I took this answer to accept because it mentions about Swift String structure bridged to NSString class. Also the usage of NSData is helpful. – Yoichi Tagaya Mar 19 '15 at 03:16
4

You can definitly use setObject:forKey:, the NSDictionary method or even setValue:forkey: which is a KVC method.

It'll work just fine.

Gil Sand
  • 5,802
  • 5
  • 36
  • 78