Erika
Erika

Reputation: 255

Best way to implement UserDefaults in iOS

I'm using UserDefaults for the first time in contributing to an iOS open source project. However, in each class where I need to set a value to a key, I find myself typing in the same line of code: let defaults = UserDefaults.standard. Is there a better way to implement UserDefaults so that I don't have to keep defining this variable in each class where I need it? In other words, is there a "best practice" when it comes to using UserDefaults?

Upvotes: 0

Views: 130

Answers (2)

Fahri Azimov
Fahri Azimov

Reputation: 11770

You could extend some mostly used class, or create a singleton to handle this repeating lines. For example, extend NSObject to have method like:

extension NSObject
{
    func save(value: Any, for key: String)
    {
        let defs = UserDefaults.standard
        defs.set(value, forKey: key)
        defs.synchronize()
    }
}

and, from any class that subclasses NSObject you can call this method. Hope this helps!

Upvotes: 1

gabriellanata
gabriellanata

Reputation: 4336

You can use UserDefaults.standard directly if you prefer, but if you are going to add / read many keys from it then it would be better to define its own variable and call the variable instead (like you are doing).

If you are thinking of creating a global variable, do not do that, the best practice is what you are doing by calling UserDefaults.standard each time. You might consider not using UserDefaults to move the values between the classes, it should ideally only be used for persistence, but that would require refactoring your app.

Upvotes: 1

Related Questions