Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is -[NSUserDefaults registerDefaults:] additive and does it overwrite values?

In other words, must I call registerDefaults in only one location in my app (e.g. when it starts up), or can I register defaults on an as-needed basis?

If it is additive, what happens when I try overwriting a value?

For example, given the following code...

[[NSUserDefaults standardUserDefaults] registerDefaults:@{@"a": @1}];
[[NSUserDefaults standardUserDefaults] registerDefaults:@{@"b": @2}];
[[NSUserDefaults standardUserDefaults] registerDefaults:@{@"b": @3}];

... what will the final defaults dictionary be?

  1. @{@"b": @3} (replacive)
  2. @{@"a": @1, @"b": @3} (additive, overwrite values)
  3. @{@"a": @1, @"b": @2} (additive, don't overwrite values)
  4. Crash, since @"b" is already defined.
like image 645
Senseful Avatar asked Jul 24 '26 03:07

Senseful


1 Answers

  1. It is additive, and overwrites values.

Example:

[[NSUserDefaults standardUserDefaults] registerDefaults:@{@"a": @1}];
[[NSUserDefaults standardUserDefaults] registerDefaults:@{@"b": @2}];
[[NSUserDefaults standardUserDefaults] registerDefaults:@{@"b": @3}];
NSAssert([[NSUserDefaults standardUserDefaults] integerForKey:@"a"] == 1, @"");
NSAssert([[NSUserDefaults standardUserDefaults] integerForKey:@"b"] == 3, @"");

The ultimate dictionary is:

@{@"a": @1, @"b": @3}

Thus, you can call it as many times as necessary.

From the documentation:

Adds the contents of the specified dictionary to the registration domain.

like image 91
Senseful Avatar answered Jul 28 '26 15:07

Senseful



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!