[Swift] How to use UserDefaults

What are User Defaults?

It permanently saves key / value pairs when you start the app. The UserDefault class provides a programmatic interface for interacting with the default system. It was mentioned in the official document. Using this default system, for example, you can set the video playback speed to your liking (playback speed 1.5 times faster?) And save it. The next time you start the app, the previous settings are the default, so the speed is still 1.5x.

Save default object

There is a save method for each type.

func set(Any?, forKey: String)
//Sets the value of the specified default key.
func set(Float, forKey: String)
//Sets the value of the specified default key to the specified float value.
func set(Double, forKey: String)
//Sets the value of the specified default key to the double value.
func set(Int, forKey: String)
//Sets the value of the specified default key to the specified integer value.
func set(Bool, forKey: String)
//Sets the value of the specified default key to the specified Boolean value.
func set(URL?, forKey: String)
//Sets the value of the specified default key to the specified URL.

To use it, call it as follows and specify the value type as well. Enter the value you want to save in the value part, and set the Key as a String type in forKey. This Key is used when pulling data.

 UserDefaults.standard.set(value, forKey:)

Calling a saved value

There is also a method to call for each type.

func object(forKey: String) -> Any?
//Returns the object associated with the specified key.
func url(forKey: String) -> URL?
func array(forKey: String) -> [Any]?
func dictionary(forKey: String) -> [String : Any]?
func string(forKey: String) -> String?
func stringArray(forKey: String) -> [String]?
func data(forKey: String) -> Data?
func bool(forKey: String) -> Bool
func integer(forKey: String) -> Int
func float(forKey: String) -> Float
func double(forKey: String) -> Double
func dictionaryRepresentation() -> [String : Any]

Use this to write code, such as putting it in a constant where you want to call it. By setting forKey earlier and entering the Key, you can get the one associated with it.

UserDefaults.standard.string(forKey:)

Change saved value

Even if you set a mutable object as the value, the value returned by UserDefaults will be immutable. Why should it be changeable! But there is a reason for this. If you do not save the default value of UserDefaults again with set (), the default value before saving will be called even if you call it with String (forKey).

I actually checked it.

import UIKit

class ViewController: UIViewController {

    @IBOutlet var textField: UITextField!
    @IBOutlet var UserDefaultsLabel: UILabel!
    @IBOutlet var contentLabel: UILabel!
    var textContent = ""
    
    override func viewDidLoad() {
        super.viewDidLoad()
        let immutable = UserDefaults.standard.string(forKey: "text")  //Values ​​returned by UserDefaults (variable but invariant). set()It cannot be changed as the default value unless it is called again with.
        UserDefaultsLabel.text = immutable
    }

    @IBAction func setButton(_ sender: Any) {
        UserDefaults.standard.set(textContent, forKey: "text") //Changing the default value
    }
    
    @IBAction func hennkouButton(_ sender: Any) {
        textContent = textField.text!
        contentLabel.text = "The value of textContent is\(textContent)"
    }
}

The button that changes the value of a variable property is the henkouButton, and the label shows the changes. setButton takes action to save the defaults in UserDefaults. Since the default value cannot be changed by just pressing the henkouButton, the change is not reflected even if the value is fetched from UserDefaules with viewDidLoad after that. By pressing henkouButton and then setButton, the change of the default value is completed, and the value is changed by viewDidLoad.

For henkouButton only

The initial value is displayed as User Defaults. Type 123 and press the henkou Button. The changes are displayed on the label at the bottom. スクリーンショット 2020-12-31 16.10.41.png

Now let's drop the app without pressing setButton. The defaults haven't changed, so the Label above remains UserDefaults. スクリーンショット 2020-12-31 16.12.29.png

Also press setButton to change the default value

When I change the default value and drop the app, ... Superb values ​​have changed! Now I know that even if it is variable, it cannot be changed unless the default value is changed with set () after changing it. スクリーンショット 2020-12-31 16.15.01.png

Reference site

https://developer.apple.com/documentation/foundation/userdefaults#1664798

Recommended Posts

[Swift] How to use UserDefaults
How to use Swift UIScrollView
[Swift] How to use SwiftLint (cocoapods)
[Swift] How to use Unwind segue
How to use Map
How to use rbenv
How to use letter_opener_web
How to use with_option
How to use fields_for
How to use java.util.logging
How to use map
How to use collection_select
[Swift] How to use Tab Bar Controller
How to use Twitter4J
How to use active_hash! !!
How to use MapStruct
How to use hidden_field_tag
How to use TreeSet
[How to use label]
How to use identity
How to use hashes
How to use JUnit 5
How to use Dozer.mapper
How to use Gradle
How to use org.immutables
[Swift] How to use one option alert
How to use java.util.stream.Collector
How to use VisualVM
How to use Map
Note how to use Swift super basic TableView
[Java] How to use Map
How to use Chain API
[Java] How to use Map
How to use Priority Queuing
[Rails] How to use enum
How to use java Optional
How to use Ruby return
[Rails] How to use enum
How to use @Builder (Lombok)
How to use java class
How to use Big Decimal
[Java] How to use Optional ②
[Java] How to use removeAll ()
How to use String [] args
[Java] How to use string.format
How to use rails join
How to use Java Map
Ruby: How to use cookies
How to use dependent :: destroy
How to use Eclipse Debug_Shell
How to use Apache POI
[Rails] How to use validation
How to use Java variables
[Rails] How to use authenticate_user!
[Rails] How to use "kaminari"
How to use GC Viewer
[Java] How to use Optional ①
How to use Lombok now
[Creating] How to use JUnit
[Rails] How to use Scope
[Swift] Use UserDefaults to save data in the app