Question

I want to understand the functionality of,

[NSUserDefaults standardUserDefaults] registerDefaults:];

Does registerDefaults method set the default value and not the actual value. For example, assuming i execute the following statements in sequence,

[[NSUserDefaults standardUserDefaults] setObject:@"1" ForKey:@"test"];  

and then call,

[NSUserDefaults standardUserDefaults] registerDefaults:[NSDictionary dictionaryWithObjectsAndKeys:@"2",@"test", nil]];  

I see that valueForKey test is still 1 and not 2. Could someone provide me a better understanding of registerDefaults or is my above anology right? If my anology is right,then does it mean that the default value is picked up only when no object is set for that specific key? Thanks in advance.

Was it helpful?

Solution

Does registerDefaults method set the default value and not the actual value

Yes. The value that you pass in the dictionary to registerDefaults: is returned to you only when there is no specific value set for that key.

When you set the value @"1" for the key @"test", you "hide" the default value registered in the registerDefaults: call.

If you do this

[NSUserDefaults standardUserDefaults] registerDefaults:@{@"a":@"1", @"b":@"2"}, nil]];
[[NSUserDefaults standardUserDefaults] setObject:@"200" ForKey:@"b"]; // Override

and then request the values for keys @"a" and @"b", you get the default value @"1" for @"a" and the specific value of @"200" for @"b".

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top