I've set some user defaults using let userDefaults = UserDefaults.standard
, and when I'm retrieving them, I can use any of these:
jobTextField.text = userDefaults.object(forKey: "job") as? String
OR I can use
jobTextField.text = userDefaults.value(forKey: "job") as? String
in what case this will has a difference? It'd be great to know when I can NOT use one of them.
Thanks a lot :)
UserDefaults caches the information to avoid having to open the user's defaults database each time you need a default value. When you set a default value, it's changed synchronously within your process, and asynchronously to persistent storage and other processes.
UserDefaults lets you store key-value pairs, where a key is always a String and value can be one of the following data types: Data, String, Number, Date, Array or Dictionary. This tutorial will show you how to use UserDefaults in Swift. UserDefaults saves its data in a local plists file on disk.
To store the string in the user's defaults database, which is nothing more than a property list or plist, we pass the string to the set(_:forKey:) method of the UserDefaults class. We also need to pass a key as the second argument to the set(_:forKey:) method because we are creating a key-value pair.
You'll need to convert the object to and from an NSData instance using NSKeyedArchiver and NSKeyedUnarchiver . For example: func savePlaces(){ let placesArray = [Place(lat: 123, lng: 123, name: "hi")] let placesData = NSKeyedArchiver. archivedDataWithRootObject(placesArray) NSUserDefaults.
value(forKey:)
is from key-value coding, and not a direct method of UserDefaults
.
Never use value(forKey:)
on UserDefaults
or Dictionary
or any other class unless you have a clearly understood need to use key-value coding to get the desired result.
When you don't have such a need, use the standard access methods provided by the class in question (such as UserDefaults object(forKey:)
.
value(forKey:)
The two are completely different. The value(forKey:)
is not a UserDefaults-only
method. It is enabled by the NSKeyValueCoding
, which, According to Apple's Documentation:
NSKeyValueCoding
is an informal protocol that objects adopt to provide indirect access to their properties. When an object is key-value coding compliant, its properties are addressable via string parameters through a concise, uniform messaging interface.
It happens that UserDefaults
is NSKeyValueCoding
compliant, so people have started (not necessarily in the correct way) using it for accessing UserDefaults
.
object(forKey:)
This is the correct way to access UserDefaults
's properties. Unless you do not have a very good reason to use value(forKey:)
, always use object(forKey:)
, or the other valid methods of UserDefaults
(i.e. string(forKey:)
).
Hope this clears things up!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With