简体   繁体   中英

swift multiple userDefaults objects

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")
    }

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

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
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM