开发者

Something odd happening with NSUserDefaults on loading app

开发者 https://www.devze.com 2023-04-13 04:04 出处:网络
I have an app that uses several different user defaults that need to be used as soon as the app loads. One of these is responsible for zooming in on a map view to the users location.

I have an app that uses several different user defaults that need to be used as soon as the app loads. One of these is responsible for zooming in on a map view to the users location.

The issue I'm having is that when I load the values of the user defaults it seems to think they are null until I change them via the settings app.

开发者_StackOverflowWhat is happening here? I'm using iOS 5, not sure if that has any impact on it. It's just really annoying because my app relies on having the data available upon loading.

NOTE: It works absolutely fine after I change/re-select the values in the settings view.


Make sure your calling synchronize after setting a value:

[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"someKey"];
[[NSUserDefaults standardUserDefaults] synchronize];

Edit to answer comments:

From the documentation for -registerDefaults::

The contents of the registration domain are not written to disk; you need to call this method each time your application starts. You can place a plist file in the application's Resources directory and call registerDefaults: with the contents that you read in from that file.

So, in -applicationDidFinishLaunching:, you can register your Root.plist defaults like this:

[[NSUserDefaults standardUserDefaults] registerDefaults:[NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Root" ofType:@"plist"]]];
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号