Although the code for NSUserDefaults seems quite simple I cannot make it work.
I have a settingViews where user can disable the sound or not. Here is my code:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
self.soundSettings.font = [UIFont rw_snapFontWithSize:24.0f];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if([defaults objectForKey:#"stateForSoundSwitch"]) {
NSLog(#"Sound is ON");
self.soundStatus.on=YES;
} else {
self.soundStatus.on=NO;
NSLog(#"Sound is OFF");
}
}
- (IBAction)soundSwitchChanged:(id)sender
{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if (self.soundStatus.on) {
NSLog(#"Sound is enabled");
[defaults setBool:true forKey:#"stateForSoundSwitch"];
}
else {
NSLog(#"Sound is disabled");
[defaults setBool:false forKey:#"stateForSoundSwitch"];
}
[defaults synchronize];
}
But even if I change the switch to FALSE, every time I log in the settings screen the value is TRUE. What am I missing?
setBool:forKey: expects a BOOL. Try using YES or NO instead of true or false (which is type bool, lowercase).
Also you should access it with boolForKey instead of objectForKey.
Your logic test will always be YES if you've ever set the object in NSUserDefaults since you're effectively testing if the key exists (i.e. not nil), not whether it is actually set to YES/NO.
In other words, change:
if ([defaults objectForKey:#"stateForSoundSwitch"]) {
to this:
if ([defaults boolForKey:#"stateForSoundSwitch"] == YES) {
Related
I'm using NSUserDefaults to save BOOLs that denote whether a mapped annotation is a "favorite". The BOOLs are saved correctly when the User quits the app and then re-launches it. However, when the User force quits (press the Home button twice and swipe up on the app) the app, the NSUserDefaults are lost. Can someone please explain why this is happening? I'm using Xcode v7.0.
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
// If annotation is displayed, the User can save/clear annotation as a favorite
if ((_acmeMotorsIsDisplayed == YES) && (_acmeMotorsIsFavorite == YES)){
_acmeMotorsIsFavorite = NO;
[[NSUserDefaults standardUserDefaults] setBool:NO forKey:#"acmeMotorsIsFavorite"];
}
else if ((_acmeMotorsIsDisplayed == YES) && (_acmeMotorsIsFavorite == NO)){
_acmeMotorsIsFavorite = YES;
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:#"acmeMotorsIsFavorite"];
}
}
-(void)loadUserDefaults{
// One of many lines of code that load user default settings
_acmeMotorsIsFavorite = [[NSUserDefaults standardUserDefaults] boolForKey:#"acmeMotorsIsFavorite"];
}
-(void)viewDidLoad {
[self loadUserDefaults];
}
I think you forget about synchronize method.
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setBool:NO forKey:#"acmeMotorsIsFavorite"];
[userDefaults synchronize];
When the user double taps Home the app delegate method applicationWillResignActive: is called, at that time synchronize NSUserDefaults:
- (void)applicationWillResignActive:(UIApplication *)application {
[[NSUserDefaults standardUserDefaults] synchronize];
}
I have an app which should only show the settings page once: when the app is opened for the first time.
Now this works, and when the user presses the middle button on the iPhone it then reopens the app and carries on from the main screen - that's great. But if I double click on the iPhone button and swipe the application off, it will then go to the settings screen again and not to where it was.
Why is it doing that? How can I make my app only show its settings once?
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
NSUserDefaults *settingsscreen = [NSUserDefaults standardUserDefaults];
[settingsscreen registerDefaults:[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES],#"firstTime", nil]];
BOOL firstTime = [settingsscreen boolForKey:#"firstTime"];
if ( firstTime==YES) {
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:#"SettingsShown"];
[[NSUserDefaults standardUserDefaults] synchronize];
self.window.rootViewController = [self.window.rootViewController.storyboard instantiateViewControllerWithIdentifier:#"SetUpNav"];
}
else
{
return YES;
}
}
Don't use if ( firstTime==YES) { based on #"firstTime", because that flag is never actually saved. You should be using the flag saved with the #"SettingsShown" key.
BOOL firstTime = [settingsscreen boolForKey:#"SettingsShown"];
if (!firstTime) {
...
Instead doing in appDelegate try to acheive it in setting Page itself
-(void) viewDidLoad {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
username = [defaults objectForKey:#"username"];
if (username != NULL ) {
[self selfLogin];
}
}
-(void)selfLogin{
nextPageController = [[NextPageViewController alloc]init];
[self.navigationController pushViewController:nextPageController animated:YES];
}
I want to show an alertview on third time my app is launched. I have searched everywhere but can't find the solution. How can I know that my app has been launched for the third time?
Thanks in Advance
you can use these methods to read and write to file with very little effort
+ (void) setSetting: (NSString *)key value: (NSString *)value {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:value forKey:[NSString stringWithFormat:#"%#", key]];
[defaults synchronize];
}
+ (NSString *) getSetting: (NSString *)key defaultVal: (NSString *)defaultVal {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *setting = [defaults stringForKey:[NSString stringWithFormat:#"%#", key]];
if (setting == nil) {
setting = defaultVal;
}
return setting;
}
you can just update a value you have stored in the user defaults each time the didFinishLaunchingWithOptions: in your appDelegate is triggered
Thats easy. Save an NSNumber in your NSUserDefaults and increase it every time you're launching your application. When it hits 3 then show an alert.
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)options {
// ...
if ([self plusPlusLaunchCount] == 3) {
[self showRateUsAlert];
}
return YES;
}
- (void)showRateUsAlert {
// show the Rate Us alert view
}
- (NSInteger)plusPlusLaunchCount {
static NSString *Key = #"launchCount";
NSInteger count = 1 + [[NSUserDefaults standardUserDefaults] integerForKey:Key];
[[NSUserDefaults standardUserDefaults] setInteger:count forKey:Key];
return count;
}
I am saving Textfield text using NSUserDefaults on button click in ViewController2
My code is
ButtonClick()
{
NSUserDefaults *userDefaults =[NSUserDefaults standardUserDefaults];
[userDefaults setObject:keyWordField.text forKey:#"Keywords"];
[userDefaults synchronize];
}
Then ViewDidLoad method i am Retrieving like this
-(void)viewDidLoad
{
NSUserDefaults *userDefaults =[NSUserDefaults standardUserDefaults];
[keyWordArray addObject:[userDefaults objectForKey:#"Keywords"]];
[userDefaults synchronize];
}
Here i am assigning this keyWordArray to tableview
like cell.textlabel.text =[keyWordArray objectAtIndex:indexPath.row];
First i entered text(First) in textfield and click button it is showing in table like
First
Second time i entered text (second) in textfield and click button it is showing table like
First
Second
Here everything working fine. The problem is when i come to viewController2 from ViewController1. It is showing last entered value only
like
Second
what going wrong here?
Try This
- (IBAction)buttonclick:(id)sender {
[keyWordArray addObject:keyWordField.text];
NSUserDefaults *userDefaults =[NSUserDefaults standardUserDefaults];
[userDefaults setObject:keyWordArray forKey:#"Keywords"];
[userDefaults synchronize];
[selt.tableView reload]; //reload the table every time a new text is added
}
-(void)viewDidLoad {
if([[NSUserDefaults standardUserDefaults] objectForKey:#"Keywords"]==nil){
keyWordArray = [[NSMutableArray alloc] init];
}
else{
keyWordArray = [[NSUserDefaults standardUserDefaults] objectForKey:#"Keywords"];
}
}
Try this,
- (IBAction)buttonclick:(id)sender {
[keyWordArray addObject:keyWordField.text];
NSUserDefaults *userDefaults =[NSUserDefaults standardUserDefaults];
[userDefaults setObject:keyWordArray forKey:#"Keywords"];
[userDefaults synchronize];
}
and
-(void)viewDidLoad
{
NSArray *array = [[NSUserDefaults standardUserDefaults] objectForKey:#"Keywords"];
if (!array) {
keyWordArray = [[NSMutableArray alloc] init];
} else {
keyWordArray = [NSMutableArray arrayWithArray:nameArray];
}
}
Since you are overriding your
[userDefaults setObject:keyWordField.text forKey:#"Keywords"];
every then and there your every object in the array will be referring to your [userDefaults setObject:keyWordField.text forKey:#"Keywords"]; object thats y the problem comes
Because if you are navigate to another viewController. since the your user default value save in second only.
After pop to back through viewDidLoad is loaded. so far its have second string only save in User Default.
that way it display second only.
You code is overwrite the last value and remove previous values from NSUserDefault. You have to use array to stored all value and you have save array into NSUserDefault.
NSMutableArray *aryDataDefault = [[NSUserDefaults standardUserDefaults] valueForKey:#"YourKey"];
[aryDataDefault addObject:textfield.text];
[[NSUserDefaults standardUserDefaults] setObject:aryDataDefault forKey:#"YourKey"];
[[NSUserDefaults standardUserDefaults] synchronize];
I am working with the simulator, and I am doing something like this when the app starts to check if it was opened for the first time:
and then checking if that key/value is empty so that this code executes only once:
NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
if([standardUserDefaults objectForKey:#"first_time_cookie"] == nil)
{
[standardUserDefaults setBool:YES forKey:#"first_time_cookie"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
but every time I run the program, it executes again. Any idea what is going wrong here?
Just a guess: standardUserDefaults is nil?
You can do different!
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:NO], #"first_time_cookie"];
[defaults registerDefaults:dict];
if ([defaults boolForKey:#"first_time_cookie"] == NO){
[defaults setBool:YES forKey:#"first_time_cookie"];
[defaults synchronize];
}
a bool is not an object. This should work
if([standardUserDefaults boolForKey:#"first_time_cookie"] == NO)
{
[standardUserDefaults setBool:YES forKey:#"first_time_cookie"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
try using
if ([[NSUserDefaults standardUserDefaults] boolForKey:#"first_time_cookie"] == false)
and let me know if it works,
gung-ho