NSUserDefaults setValue and objectForKey

Can you use:

[[NSUserDefaults standardUserDefaults] setValue:objectID forKey:"objectID"]

to set an object to NSUserDefaults

and then retrieve that object using:

objectType *tempObject = [[NSUserDefaults standardUserDefaults] objectForKey:@"objectID"]


So, to clarify, I ask, what if I use setObject

, can I use valueForKey

? Or vice versa, can I use setValue

and then get it with objectForKey


And why you / can't do it?

If I read correctly, setObject

/ objectForKey

deals with NSDictionary

and setValue

/ valueForKey

works with KVC, right?

I'm just trying to understand the difference between the two a little better.

Thank. Greetings.


source to share

1 answer

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 objectID

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


Whereas it 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 valueForKey

and setValueForKey

to behave like objectForKey


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.



All Articles