2

I have one application that sets preferences. It uses those prefs, and so does another application. When I use the following code in the second application, it reads the preferences correctly once.

    NSUserDefaults* settings = [NSUserDefaults standardUserDefaults];
    [settings addSuiteNamed:@"com.WVS.Wrestling-Tools"];
    [settings synchronize]; // this just a shot in the dark.. didn't work

    [self setScoreboardIndex:[settings integerForKey:@"matName"]];

On subsequent calls of the same code, I get the [settings integerForKey:@"matName"] is always the value that was first read.

In the first application, I'm using the Shared User Defaults Controller to read/write the preferences. Not sure if that matters to this issue or not.

How can I force the second application to always get the most recent values?

Adam
  • 913
  • 1
  • 9
  • 26

1 Answers1

4

You should be able to call +[NSUserDefaults resetStandardUserDefaults] in the second program to force +[NSUserDefaults standardUserDefaults] to create a new instance and reload values from disk the next time it's called. Calling -synchronize in the first program is the correct approach to make sure the updated defaults are written to disk (I'm not sure how NSUserDefaultsController behaves in this regard).

Note that calling +[NSUserDefaults resetStandardUserDefaults] every time you access the standardUserDefaults may result in a performance penalty if you do so frequently, since it will presumably mean a disk hit on every read.

Andrew Madsen
  • 21,309
  • 5
  • 56
  • 97
  • That did it. I added the synchronize to the first program, so that it executes only when it needs to, which is rarely. Thanks! – Adam May 19 '12 at 18:48
  • 1
    `synchronize` is both read and write, so using that in the second program as well would cause new values to be picked up. I'm not sure if that will be any better than `resetStandardUserDefaults`, though -- I think the only difference will be not creating a new `NSUserDefaults` object. – jscs May 19 '12 at 18:51
  • Not working for me. When I synchronize defaults, change my plists content vie Xcode, then call `resetStandardUserDefaults` and it reverts back to the pre-edited state... – Julian F. Weinert Feb 24 '15 at 15:17
  • 1
    @Julian, the preferences system in OS X has changed recently (in 10.9, IIRC) and now does much more aggressive caching. Manually editing preferences plists is not at all reliable anymore. Instead, you should only make changes via the `NSUserDefaults` (or `CFPreferences`) API, or using the `defaults` command-line tool. – Andrew Madsen Feb 24 '15 at 18:23
  • @AndrewMadsen: sure, that's fairly simple. But during dev it's sometimes useful to be able to wipe the prefs like fresh install. Thus cache killing would be really useful – Julian F. Weinert Mar 04 '15 at 00:04