What is the use of -[NSUserDefaults registerDefaults:]?

Enrico Susatyo picture Enrico Susatyo · Feb 8, 2011 · Viewed 23.6k times · Source

What is the difference between:

[[NSUserDefaults standardUserDefaults] registerDefaults:
  [NSDictionary dictionaryWithObjectAndKey:anObject, @"something"]];

And this:

[[NSUserDefaults standardUserDefaults] setObject:anObject forKey:@"something"];

Answer

LuckyLuke picture LuckyLuke · Feb 8, 2011

The difference is that the first code-snippet you register defaults that will be used when the user has not made any changes to the "property".

So if you want to provide let's say a "property" with the key name 'Welcome message', you could instead of having the property returning nil insert a default message 'Welcome first-time user' that will be displayed when there have been no changes to the property.

This will simplify your logic because you don't need to write an if test to check if the "property" returns nil and then make another message if this is the case.

NSString *greeting = [[NSUserDefaults standardUserDefaults] stringForKey:@"Greeting"];

if(greeting == nil) {
    NSLog(@"Welcome first-time user!");
}

The second code-snippet you posted is for setting the property to another value. You will have different set methods (setString, setObject, setBoolean) to set values depending on your program state in the Userdefaults.

EDIT-----Updates as requested in comment.

The first method is for registering values to defaults, as the name implies. The first time you access the property with some key name the value will be either nil for objects, false for booleans or 0 for numbers. Instead of doing a lot of tests and so on to so if the values is not set in the program, and then do something "default" action such as the example above, you can ship your application with some already predefined values for these keys.

A typical place to put the registerDefaults is in the initializer-method in the appDelegate.

Then somewhere in your program you may want to set the values of these fields then you use the setObject, setString, setBoolean...and for retrieving you use stringForKey, objectForKey...

Think of it as this

The registerDefaults is the constructor where you may supply sensible values for the object, otherwise you get some defaults which I already wrote. Then later if you want to change the object's attributes you do NOT use the "constructor" but the set/get methods.