NSUserDefaults setValue and objectForKey
Can you use:
[[NSUserDefaults standardUserDefaults] setValue:objectID forKey:"objectID"]
to set an object to
and then retrieve that object using:
objectType *tempObject = [[NSUserDefaults standardUserDefaults] objectForKey:@"objectID"]
So, to clarify, I ask, what if I use
, can I use
? Or vice versa, can I use
and then get it with
And why you / can't do it?
If I read correctly,
works with KVC, right?
I'm just trying to understand the difference between the two a little better.
source to share
From the documentation
- (void) setObject: (id) forKey value: (NSString *) defaultName
The value parameter can only be property list objects: NSData strong>, NSString , NSNumber , NSDate , NSArray, or NSDictionary . For NSArray and NSDictionary objects, their contents must be property list objects. Cm
This works from
setObject / objectForKey
where you add objects inside NSUserDefaults
Your example will work if
is only one of the six types above. What for? because NSUserDefaults takes this object and stores it on the filesystem in the plist file and so it needs to know how to deal with this object in order to save it. If you added a custom object then NSUserDefaults will not be able to save it to the file system
setValue / valueForKey
works with the properties of the NSUserDefaults class itself, not the objects inside it that you want to keep
So, to clarify, I ask that if I use setObject, can I use valueForKey? Or conversely, can I use setValue and then retrieve it using objectForKey?
Short answer: Yes you can
Long answer: NSUserDefaults override
to behave like
However, if the key is the same as the property in NSUserDefaults then conflicts can arise ... but in the case of NSUserDefaults where it has no properties, you can use it. But in my opinion you should use standard methods for convenience, especially if it is not documented.
source to share