8

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

2 Answers 2

22

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

Sign up to request clarification or add additional context in comments.

1 Comment

I noticed in WWDC 2017 - session 236 at around 6:30, or slide 52 if you download the PDF, they use value(forKey:) in the example for using key paths with Swift 4 and UserDefaults. Why is that? And what would be the reasons for using it over object(forKey:)?
16

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


2. 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!

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.