Objective-C NSUserDefaults caching prevents anothe

2019-02-25 21:29发布

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?

1条回答
虎瘦雄心在
2楼-- · 2019-02-25 21:49

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.

查看更多
登录 后发表回答