Reputation: 8651
I am using this struct to save a token in my app:
struct LocalStore {
static let userDefaults = NSUserDefaults.standardUserDefaults()
static func saveToken(token: String) {
userDefaults.setObject(token, forKey: "tokenKey")
}
static func getToken() -> String? {
return userDefaults.stringForKey("tokenKey")
}
static func deleteToken() {
userDefaults.removeObjectForKey("tokenKey")
}
}
I know that I wan overwrite existing saved object but can I save multiple objects? Like this:
static func saveToken(token: String) {
userDefaults.setObject(token, forKey: "tokenKey")
}
static func saveFirstName(firstName: String) {
userDefaults.setObject(firstName, forKey: "lastNameVal")
}
static func saveLastName(lastName: String) {
userDefaults.setObject(lastName, forKey: "firstNameVal")
}
Upvotes: 0
Views: 2097
Reputation: 52227
The accepted answer is right, but I want to show another way of how to deal with NSUserDefaults in Swift.
By using computed properties instead of methods or functions, it is easy to use NSUserDefaults as the backing variable — and as all set and get operations are performed through this property, no further code is needed to ensure that the property has the correct value.
From production code:
var sorting:DiscoverSortingOrder {
set {
NSUserDefaults.standardUserDefaults().setInteger(newValue.rawValue, forKey: "DiscoverSorting")
refresh() // will trigger reloading the UI
}
get {
if let s = DiscoverSortingOrder(rawValue: NSUserDefaults.standardUserDefaults().integerForKey("DiscoverSorting")){
return s
}
return .New // Default value
}
}
Upvotes: 1
Reputation: 644
Yes, as long as it has a different key. This is possible, however, from your example, you are saving your token object to multiple keys. There is nothing wrong with that if that is your intention.
User defaults is a form of persistent storage that can save many types of values (not just Strings).
Upvotes: 2