erad
erad

Reputation: 1786

NSUserDefaults setValue and objectForKey

Can you use:

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

to set an object in the NSUserDefaults and then retrieve that object using:

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

?

So to clarify, What I'm asking is that if I use setObject, can I use valueForKey ? Or vice versa, can I use setValue and then retrieve it using objectForKey ?

And why can/can't you do that?

If I read correctly, setObject / objectForKey deals with NSDictionary and setValue / valueForKey deals with KVC, correct?

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

Thanks. Cheers.

Upvotes: 3

Views: 3212

Answers (1)

Hani Ibrahim
Hani Ibrahim

Reputation: 1449

From the documentation

- (void)setObject:(id)value forKey:(NSString *)defaultName

The value parameter can be only property list objects: NSData, NSString, NSNumber, NSDate, NSArray, or NSDictionary. For NSArray and NSDictionary objects, their contents must be property list objects. See

That works with setObject / objectForKey where you are adding objects inside the NSUserDefaults

Your example will work if objectID is only one type of the six above. Why? because NSUserDefaults takes that object and save it to the file system in a plist file and so it needs to know how to deal with that object to save it. If you added a custom object then the NSUserDefaults will not be able to save that on the file system

.

While setValue / valueForKey works with the properties of the class NSUserDefaults itself not with the objects inside it that you want to save


Edit

So to clarify, What I'm asking is that if I use setObject, can I use valueForKey ? Or vice versa, can I use setValue and then retrieve it using objectForKey ?

Short Answer: Yes You can

Long Answer: NSUserDefaults override the valueForKey and setValueForKey to behave like objectForKey and setObjectForKey

However if the key is the same as a property in the NSUserDefaults then conflicts may happenes ... but in the case of NSUserDefaults where it has no properties then you can use it. But in my opinion you should use the standard methods for readably specially if that is not documented

Upvotes: 8

Related Questions