Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 369
Yoichi Tagaya Avatar asked Mar 18 '15 15:03

Yoichi Tagaya


People also ask

What is NSUserDefaults in Swift?

Overview. The NSUserDefaults class provides a programmatic interface for interacting with the defaults system. The defaults system allows an app to customize its behavior to match a user's preferences. For example, you can allow users to specify their preferred units of measurement or media playback speed.

How do you save a Userdefault string in Swift?

To store the string in the user's defaults database, which is nothing more than a property list or plist, we pass the string to the set(_:forKey:) method of the UserDefaults class. We also need to pass a key as the second argument to the set(_:forKey:) method because we are creating a key-value pair.


2 Answers

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().set(userName, forKey: "userName")
UserDefaults().set(userAddress, forKey: "userAddress")
UserDefaults().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
like image 134
Leo Dabus Avatar answered Oct 04 '22 21:10

Leo Dabus


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)")
}
like image 37
Daniel Storm Avatar answered Oct 04 '22 20:10

Daniel Storm