问题
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 :)
回答1:
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:)
.
回答2:
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!
来源:https://stackoverflow.com/questions/42472327/what-is-the-difference-between-objectforkey-and-valueforkey-in-userdefault