Save checkbox values - ios

As many others here I am new to Xcode and would like to ask a basic question. When checking a box and leaving Xcode, this value is not saved (unchecked box) when I reopen the Xcode project.
I have seen different discussions here: e.g. how to save a checkbox value check/uncheck to NSUserDefaults but it is not working in my code. Do you have a hint where the problem is?
In my .h I have created an instance of a BOOL (called “checked“) and a UIButton is connected both as an IBAction and as an IBOutlet.
- (void)viewDidLoad{
checked = NO;
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:#"Negative"];
BOOL checked = [[NSUserDefaults standardUserDefaults] boolForKey:#"Negative"];
[[NSUserDefaults standardUserDefaults] synchronize];
[super viewDidLoad];
NSUserDefaults *defaults70 = [NSUserDefaults standardUserDefaults];
checked = [defaults70 boolForKey: #"boxIsChecked70"];
[self checkTheBox];
[self updateLabels];}
- (IBAction)CheckCOUTCheckButton:(id)sender {
NSUserDefaults *defaults70 = [NSUserDefaults standardUserDefaults];
if (! checked) {
[_CheckBoxCOUTButton setImage:[UIImage imageNamed:#"Checkboxcheckedimage.png"] forState:UIControlStateNormal];
checked = YES;
[defaults70 setBool:checked forKey:#"boxIsChecked70"];}
else if (checked) {
[_CheckBoxCOUTButton setImage:[UIImage imageNamed:#"Checkboxuncheckedimage.png"] forState:UIControlStateNormal];
checked = NO;
[defaults70 setBool:checked forKey:#"boxIsChecked70"];}
[defaults70 synchronize];}
- (void) checkTheBox {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if (! checked) {
[_CheckBoxCOUTButton setImage:[UIImage imageNamed:#"Checkboxuncheckedimage.png"] forState:UIControlStateNormal];
}
else if (checked) {
[_CheckBoxCOUTButton setImage:[UIImage imageNamed:#"Checkboxcheckedimage.png"] forState:UIControlStateNormal];
}
- (IBAction)ClearAllFields:(id)sender {
[_CheckBoxCOUTButton setImage:[UIImage imageNamed:#"Checkboxuncheckedimage.png"] forState:UIControlStateNormal];
checked = NO;}

Your problem is an problem of scope. You are defining a second variable called checked and confusing which one you're setting.
- (void)viewDidLoad{
checked = NO;
in this line you are setting the property - ie the self.checked value to NO.
BOOL checked = [[NSUserDefaults standardUserDefaults] boolForKey:#"Negative"];
[[NSUserDefaults standardUserDefaults] synchronize];
in this line however you are declaring a NEW local variable that will only exist within viewDidLoad.
try removing the BOOL before it. When viewDidLoad returns this local variable will go out of scope and disappear.
checked = [[NSUserDefaults standardUserDefaults] boolForKey:#"Negative"];
[[NSUserDefaults standardUserDefaults] synchronize];
so later on when you set the checkbox as part of checkTheBox you're reading the property, not your local variable that you set.
let me know if this isn't clear.

I am not sure if this is your only problem, but in your viewDidLoad, you are basically setting a value before you're reading it:
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:#"Negative"];
BOOL checked = [[NSUserDefaults standardUserDefaults] boolForKey:#"Negative"];
You probably want to do this:
BOOL checked = [[NSUserDefaults standardUserDefaults] boolForKey:#"Negative"];

Related

iOS: Force view reload after locale change

I have setup my app to support a base internationalization for English and added a local for Spanish. I'm trying to provide an option to force the app to use a locale select by the user via a segmented control.
What I would like to do is have the screen "refresh" or "redraw" with the new selected locale.
Here is my action for the segmented control:
- (IBAction)segmentSwitch:(id)sender {
UISegmentedControl *segmentedControl = (UISegmentedControl *) sender;
NSInteger selectedSegment = segmentedControl.selectedSegmentIndex;
NSUserDefaults *prefs;
prefs = [NSUserDefaults standardUserDefaults];
if (selectedSegment == 0) {
[prefs setObject:#"en" forKey:#"language"];
[[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithObjects:#"en", nil] forKey:#"AppleLanguages"];
[[NSUserDefaults standardUserDefaults] synchronize];
NSLog(#"English");
}
else
{
[prefs setObject:#"es" forKey:#"language"];
[[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithObjects:#"es", nil] forKey:#"AppleLanguages"];
[[NSUserDefaults standardUserDefaults] synchronize];
NSLog(#"Spanish");
}
[self.view setNeedsDisplay];
}
My hope is that the screen would refresh and display the selected language view. If I close out the app and restart, it does display new view.
Here is my viewWillAppear:
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
// get the saved language preference
NSUserDefaults *prefs;
prefs = [NSUserDefaults standardUserDefaults];
NSString *stringVal = [prefs stringForKey:#"language"];
// Make sure we have a valid value
if (stringVal != nil) {
// Set the language preference
[[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithObjects:stringVal, nil] forKey:#"AppleLanguages"];
[[NSUserDefaults standardUserDefaults] synchronize]; //to make the change immediate
// Turn on the appropriate segment
if ([stringVal isEqual: #"en"]) {
NSLog(#"English");
languageSwitch.selectedSegmentIndex = 0;
} else {
NSLog(#"Spanish");
languageSwitch.selectedSegmentIndex = 1;
}
} else {
// default to English
languageSwitch.selectedSegmentIndex = 0;
[[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithObjects:#"en", nil] forKey:#"AppleLanguages"];
[[NSUserDefaults standardUserDefaults] synchronize]; //to make the change immediate
}
}
I had thought that following would force a screen refresh but it doesn't seem to be working:
[self.view setNeedsDisplay];
Any thoughts or suggestions would be appreciated. Thanks in advanced.

Xcode NSUserDefaults settings lost when app is force quit

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];
}

save UIButton state iOS

I have a UIButton
- (IBAction)checkButton:(id)sender {
if (!checked) {
[checkBoxButton setImage:[UIImage imageNamed:#"check.png"] forState:UIControlStateNormal];
checked = YES;
} else if (checked) {
[checkBoxButton setImage:[UIImage imageNamed:#"uncheck.png"] forState:UIControlStateNormal];
checked = NO;
}
}
I want to save the user input, weather the button is checked or not, even after the app closes. Help me with codes anyone? I don't know the codes to use NSUserDefaults for saving BOOL state.
Use it by below way:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setBool: checked forKey:#"Status"];
[defaults synchronize];
To retrieve it,
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
BOOL state = [defaults boolForKey:#"Status"];
Set images for both Normal and selected state of a button as
[checkBoxButton setImage:[UIImage imageNamed:#"check.png"] forState:UIControlStateSelected];
[checkBoxButton setImage:[UIImage imageNamed:#"uncheck.png"] forState:UIControlStateNormal];
and in IBAction set
- (IBAction)checkButton:(id)sender {
if (!checked) {
[checkBoxButton setSelected:NO];
checked = YES;
} else if (checked) {
[checkBoxButton setSelected:YES];
checked = NO;
}
}
Here is an Example:
if ([[NSUserDefaults standardUserDefaults] boolForKey:hasLaunchedOnceKey])
{
[[NSUserDefaults standardUserDefaults] setBool:TRUE forKey:hasLaunchedOnceKey];
[[NSUserDefaults standardUserDefaults] synchronize]; //Saves the data
}
Where I have:
static NSString *hasLaunchedOnceKey = #"HasLaunchedOnce";
Declared before the #implementation statement.
See this for an extensive tutorial.
**Note: You do not need to declare anything in any sort of plist files afaik. You can simply check for and set these keys and they will be dynamically created if they don't exist. Works that way for me anyways.
Happy programming!
My way is too easy .. You don't need to take any other variable. On initialise set your button tag ZERO and after use this.
- (IBAction)checkButton : (id)sender {
if ([sender tag] == 0) {
[sender setImage:[UIImage imageNamed:#"check.png"] forState:UIControlStateNormal];
[sender setTag:1];
} else {
[sender setImage:[UIImage imageNamed:#"uncheck.png"] forState:UIControlStateNormal];
[sender setTag:0];
}
}
Thanks & Cheers .. May be helpfull..

NSUserDefaults Saving only last entered data

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];

Detect if user opened the View for the first Time In iOS

I know how I can detect if the application first time opened using NSUserDefault:
BOOL didRunBefore = [[NSUserDefaults standardUserDefaults] boolForKey:#"didRunBefore"];
if (!didRunBefore) {
//Your Launch Code
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:#"didRunBefore"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
The Issue: I want an Alert for ever view explaining about what features it contains and only open this alert when the app is first launched?
As an OOP programmer you can make a common public method.
+ (BOOL)checkWhetherRunBefore:(NSString *)key
{
return [[NSUserDefaults standardUserDefaults] boolForKey:key];
}
+ (void)hasRunForMyClass:(NSString *)key
{
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:key];
[[NSUserDefaults standardUserDefaults] synchronize];
}
And in your ViewController , you can code in the viewWillAppear or viewDidAppear like this :
- (void)viewWillAppear
{
if(![HelpController checkWhetherRunBefore:NSStringFromClass([self class])])
{
//do your thing
[HelpController hasRunForMyClass:NSStringFromClass([self class])]
}
}
You just need to put your code in viewDidLoad
viewDidLoad will run only one time when app load your view. (except low memory)
Next time you load the view again in viewDidLoad, you can check bool didRunBefore
You can use any key you want.
In FirstViewController:
BOOL didRunBefore = [[NSUserDefaults standardUserDefaults] boolForKey:#"FirstViewController_didRunBefore"];
if (!didRunBefore) {
//Your Launch Code
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:#"FirstViewController_didRunBefore"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
In SecondViewController:
BOOL didRunBefore = [[NSUserDefaults standardUserDefaults] boolForKey:#"SecondViewController_didRunBefore"];
if (!didRunBefore) {
//Your Launch Code
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:#"SecondViewController_didRunBefore"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
yo have to need to detect application first launch, you can detect t like this
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if (![defaults objectForKey:#"firstRun"])
[defaults setObject:[NSDate date] forKey:#"firstRun"];
[[NSUserDefaults standardUserDefaults] synchronize];
You can then test for it later...
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if([defaults objectForKey:#"firstRun"])
{
// do something or not...
}

Resources