Load state of UISwitch from NSUserDefaults - ios

I have managed to change the state of my UISwitch and save to NSUserDefaults.
My UISwitch is in a different view from the main view and when I flip between views, my UISwitch button always appears ON even though the state may be OFF.
- (IBAction)truthonoff:(id)sender {
if(_truthonoff.on) {
// lights on
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setValue:#"yes" forKey:#"truthonoff"];
[defaults synchronize];
self.status.text = #"on";
}
else {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setValue:#"no" forKey:#"truthonoff"];
[defaults synchronize];
self.status.text =#"off";
}
}
And this is how I'm loading the button in the second view controller:
NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
self.text.text=[defaults objectForKey:#"truthonoff"];
How can I ensure the UISwitch state represents the value in the NSUserDefaults (i.e. when it's OFF it shows as OFF and when ON shows as ON)?

Try this:
NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
[self.valueSwitch setOn:[[defaults objectForKey:#"truthonoff"] boolValue] animated:YES];
[self.valueSwitch addTarget:self action:#selector(stateSwitched:) forControlEvents:UIControlEventValueChanged];
In stateSwitched do this:
-(void)stateSwitched:(id)sender {
UISwitch *tswitch = (UISwitch *)sender;
NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
[defaults setObject: tswitch.isOn ? #"YES" : #"NO" forKey:#"truthonoff"];
[defaults synchronize];
}
Hope this helps .. :)

A little too late but Instead of doing like the answer you have accepted:
NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
[defaults setObject: tswitch.isOn ? #"YES" : #"NO" forKey:#"truthonoff"];
[defaults synchronize];
the right way would be:
NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
[defaults setBool:tswitch.isOn forKey:#"truthonoff"];
[defaults synchronize];
This save you from checking the value of the boolean, since NSUserDefaults can take boolean value.
Also it would be easier to retrieve the boolean:
bool truthonoff = [defaults boolForKey:#"truthonoff"];
Read up some more on boolForKey

Connect your your UISwitch to an IBOutlet in your ViewController.
You can (un-)set the switch with:
[mySwitch setOn:TRUE animated:TRUE];
Method Reference

Related

Can't set NSUserDefaults value through variable in IOS

In my iOS app when I'm logging in I used set UserID and loginstatus into NSUserDefaults like this.
#implementation Login{
NSInteger UserId;
NSUserDefaults *preferences;
}
- (IBAction)LogInClick:(UIButton *)sender {
[preferences setInteger:UserId forKey:#"UserId"]; //UserId=40;
[preferences setBool:YES forKey:#"loginstatus"];
[preferences synchronize];
NSLog(#"All NSUserDefaults: %#", [[NSUserDefaults standardUserDefaults] dictionaryRepresentation]);
NSString *uID = [preferences stringForKey:#"UserId"];
NSLog(#"UserID: %#",uID);
}
But the values are not setting in the NSUserDefaults. I tried to log all NSUserDefaults value and also the single UserID value but all fields are coming null.
Later I use this code to logout
- (IBAction)LogOutClick:(UIButton *)sender {
[[NSUserDefaults standardUserDefaults] setObject:0 forKey:#"UserId"];
[[NSUserDefaults standardUserDefaults] setObject:NO forKey:#"loginstatus"];
/* [preferences setInteger:0 forKey:#"UserId"];
[preferences setBool:NO forKey:#"loginstatus"];
[preferences synchronize];*/
NSLog(#"All NSUserDefaults: %#", [[NSUserDefaults standardUserDefaults] dictionaryRepresentation]);
}
First when i logged out it all sets to zero and now the values are not setting. Can anybody tell me what the problem is?
That's because NSUserDefaults *preferences; is just a pointer. And it's value is nil, I presume. You should initialize it. For instance:
- (IBAction)LogInClick:(UIButton *)sender {
preferences = [NSUserDefaults standardUserDefaults];
[preferences setInteger:UserId forKey:#"UserId"]; //UserId=40;
[preferences setBool:YES forKey:#"loginstatus"];
[preferences synchronize];
...
May be a more logical place to initialize preferences would be an init method, or something else that you would consider appropriate for this purpose.
You haven't get the standard userdefaults reference. Change this method
- (IBAction)LogInClick:(UIButton *)sender {
preferences = [NSUserDefaults standardUserDefaults];
[preferences setInteger:UserId forKey:#"UserId"]; //UserId=40;
[preferences setBool:YES forKey:#"loginstatus"];
[preferences synchronize];
NSLog(#"All NSUserDefaults: %#", [[NSUserDefaults standardUserDefaults] dictionaryRepresentation]);
NSString *uID = [preferences stringForKey:#"UserId"];
NSLog(#"UserID: %#",uID);
}

change uiswitch based on state of another uiswitch

I basically have two switch buttons that i want the user to select from either two player or group play. However i dont want the user to be able to select both of these so idealy when the user clicks one the other turns off. How would be best to implement this?
-(void)stateSwitchedtwoplayer:(id)sender {
UISwitch *tswitch = (UISwitch *)sender;
NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
[defaults setObject: tswitch.isOn ? #"YES" : #"NO" forKey:#"twoplayerswitch"];
[defaults synchronize];
}
-(void)stateSwitchedgroup:(id)sender {
UISwitch *tswitch = (UISwitch *)sender;
NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
[defaults setObject: tswitch.isOn ? #"YES" : #"NO" forKey:#"groupswitch"];
[defaults synchronize];
}
Do you have references for both switches ?
If yes, it will be something like this :
-(void)stateSwitchedtwoplayer:(id)sender {
UISwitch *tswitch = (UISwitch *)sender;
self.switchGroup.on =! tswitch.isOn; //reference to group switch
NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
[defaults setBool: tswitch.isOn forKey:#"twoplayerswitch"];
[defaults setBool: !tswitch.isOn forKey:#"groupswitch"];
[defaults synchronize];
}
-(void)stateSwitchedgroup:(id)sender {
UISwitch *tswitch = (UISwitch *)sender;
self.switchTwoPlayer.on =! tswitch.isOn; //reference to two players switch
NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
[defaults setBool: tswitch.isOn forKey:#"groupswitch"];
[defaults setBool: tswitch.isOn forKey:#"twoplayerswitch"];
[defaults synchronize];
}
but if you want that both switches can be off, then you just need to change it on
self.switchGroup.on =! tswitch.isOn == YES; //reference to group switch
self.switchTwoPlayer.on =! tswitch.isOn == YES; //reference to two players switch
You would implement this with KVO. You can find documentation at: https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/KeyValueObserving/Articles/KVOCompliance.html. But i would suggest you not to.
You should implement some UISegmentedControl for these type of operations. Why don't you take a look at: https://developer.apple.com/library/ios/documentation/uikit/reference/UISegmentedControl_Class/Reference/UISegmentedControl.html.

Why are my uiswitch's getting confused

I have 4 ui switches on one view controller and two are working perfect however the last two have setup so you can only click on either group or two player however when you click on two player on then click save and go back in it turns both switches on however if you do the same in group it dosnt not do this?
Anyone see what im doing wrong here?
-(void)stateSwitched:(id)sender {
UISwitch *tswitch = (UISwitch *)sender;
NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
[defaults setObject: tswitch.isOn ? #"YES" : #"NO" forKey:#"truthonoff"];
[defaults synchronize];
}
-(void)stateSwitcheddare:(id)sender {
UISwitch *tswitch = (UISwitch *)sender;
NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
[defaults setBool: tswitch.isOn forKey:#"groupswitch"];
[defaults setBool: tswitch.isOn forKey:#"twoplayerswitch"];
[defaults synchronize];
}
-(void)stateSwitchedtwoplayer:(id)sender {
UISwitch *tswitch = (UISwitch *)sender;
//turns two player off when on and soforth
self.groupswitch.on =! tswitch.isOn;
NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
[defaults setBool: tswitch.isOn forKey:#"twoplayerswitch"];
[defaults setBool: !tswitch.isOn forKey:#"groupswitch"];
[defaults synchronize];
}
-(void)stateSwitchedgroup:(id)sender {
UISwitch *tswitch = (UISwitch *)sender;
//turns two player off when on and soforth
self.twoplayerswitch.on =! tswitch.isOn;
NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
[defaults setBool: tswitch.isOn forKey:#"groupswitch"];
[defaults setBool: tswitch.isOn forKey:#"twoplayerswitch"];
[defaults synchronize];
}
just realised im running this on viewdidload which may be affecting it?
[self.twoplayerswitch setOn:[[defaults objectForKey:#"twoplayerswitch"] boolValue] animated:YES];
[self.twoplayerswitch addTarget:self action:#selector(stateSwitchedtwoplayer:) forControlEvents:UIControlEventValueChanged];
[self.groupswitch setOn:[[defaults objectForKey:#"groupswitch"] boolValue] animated:YES];
[self.groupswitch addTarget:self action:#selector(stateSwitchedgroup:) forControlEvents:UIControlEventValueChanged];
In the stateSwitchedtwoplayer method, you potentially change the state of self.groupswitch.on, but you don't save the change to NSUserDefaults.

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

ios - setting a standardUserDefaults while running the simulator does not save the data

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

Resources