NSUserDefaults has integerForKey:
, setInteger:forKey:
and stringForKey:
, but does not have setString:forKey:
.
How
You can definitly use setObject:forKey:
, the NSDictionary
method or even setValue:forkey:
which is a KVC
method.
It'll work just fine.
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)")
}
update: Xcode 7.0.1 • Swift 2.0
let myString = "Hello World"
NSUserDefaults.standardUserDefaults().setObject(myString, forKey: "myString")
if let myLoadedString = NSUserDefaults.standardUserDefaults().stringForKey("myString") {
print(myLoadedString) // "Hello World"
}
The nice thing about Swift is that it allows to you to easily extend the language. You can create your own setString(forKey:), setDate(forKey:), etc... creating a NSUserDefaults extension as follow:
extension NSUserDefaults {
func setString(string:String, forKey:String) {
setObject(string, forKey: forKey)
}
func setDate(date:NSDate, forKey:String) {
setObject(date, forKey: forKey)
}
func dateForKey(string:String) -> NSDate? {
return objectForKey(string) as? NSDate
}
}
let name = "Chris Lattner"
let address = "1 Infinite Loop, Cupertino, CA 95014, United States"
let dob = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!.dateWithEra(1, year: 1978, month: 1, day: 1, hour: 0, minute: 0, second: 0, nanosecond: 0)!
NSUserDefaults().setString(name, forKey: "userName")
NSUserDefaults().setString(address, forKey: "userAddress")
NSUserDefaults().setDate(dob, forKey: "userDOB")
let loadedUserName = NSUserDefaults.standardUserDefaults().stringForKey("userName") ?? ""
let loadedUserAddress = NSUserDefaults.standardUserDefaults().stringForKey("userAddress") ?? ""
let loadedUserDOB = NSUserDefaults.standardUserDefaults().dateForKey("userDOB") ?? NSDate.distantPast()
print(loadedUserName) // "Chris Lattner"
print(loadedUserAddress) // "1 Infinite Loop, Cupertino, CA 95014, United States"
print(loadedUserDOB.descriptionWithLocale(NSLocale(localeIdentifier: "en_US"))) // "Sunday, January 1, 1978 at 12:00:00
The reason that setObject can be used to apply a string is found in the discussion of the reference:
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.
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).