I have one Toggle Switch in my settings bundle, but it is not working for first time. When i changed the value once again in the settings it is working corrctly.
Even i synchronize before using the value:
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults synchronize];
if([userDefaults boolForKey:@"KeyName"]) {
//Do Some Work
}
What i have to do now?
I assume you are facing this issue since you haven't registered your default values.
[[NSUserDefaults standardUserDefaults] registerDefaults:[NSDictionary dictionaryWithObjectsAndKeys:@"defaultValueFOrKey", @"Key", nil]];
In normal practice, we will create a plist file with the default values for all keys in settings bundle for this purpose and register it as
[[NSUserDefaults standardUserDefaults] registerDefaults:[NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Defaults" ofType:@"plist"]]];
I think what you are encountering here is the rather strange issue that the settings in your settings bundle are not loaded until the first time the user runs the settings application.
Straight from Apple:
For newly installed applications, default preference values from the application’s Settings bundle are not set until the Settings application runs. This means that if the user runs your application before running Settings, the default values specified in your Settings bundle are unavailable.
For more info see: Apple's Documentation
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With