My NSUserDefaults code does not work - ios

When I try to use NSUserDefaults on two different screens, the NSUserDefaults does not apply and there is not an error that comes up. Basically, I want the next level to be available only after the first one is completed.
Here is my code:
View1:
- (void)viewDidLoad {
[super viewDidLoad];
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSInteger level1Complete = [prefs integerForKey:#"levelComplete"];
if (level1Complete == 11) {
button2.hidden = NO;
}
}
View2:
if (number11 == 5) {
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setInteger:11 forKey:#"levelComplete"];
[prefs synchronize];
}
Please note: the game play itself is view2 and the level select is view1.

[[NSUserDefaults standardUserDefaults] setValue:#"11" forKey:#"levelComplete"];
if you can save it as a value and when you fetch it then convert it into integer.
All The Best!!

Related

Save switch position after closing app

I wanted to know how to save the position of a switch to close and open the application ?
-(IBAction)switch_poids_passagers:(UISwitch *)sender {
NSString *poids_passagers_total;
if(sender.on) {
poids_passagers_total = #"1";
} else {
poids_passagers_total = #"2";
}
[[NSUserDefaults standardUserDefaults] setObject:poids_passagers_total forKey:#"poids_passagers_total"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
NSUserDefaults can save and retrieve BOOLS with a pair methods it provides:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setBool:self.myUISwitch.on forKey:#"switchValue"];
// ...
Later on, maybe in viewWillAppear...
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
BOOL switchValue = [defaults boolForKey:#"switchValue"];
self.myUISwitch.on = switchValue;

Obj C - NSUserDefaults won't give back values to calculate, after loading the view

I am stuck with little problem. I have basic calculating app.
Viewcontroller.m
#import "ViewController.h"
#interface ViewController () <UITextFieldDelegate, UIAlertViewDelegate>
#end
#implementation ViewController
-(void)textFieldDidEndEditing:(UITextField *)textField
{
self.currentSettings = _currentSettings;
[self calculateThePrice];
}
-(void)calculateThePrice
{
float wynik = self.currentSettings.kwh * self.currentSettings.price;
self.priceLabel.text = [NSString stringWithFormat:#"%.02f %#", wynik , self.currentSettings.currency];
}
SettingsVC.m
#import "SettingsVC.h"
#interface SettingsVC () <UITextFieldDelegate>
#end
#implementation SettingsVC
#pragma mark - UserDefaults Implementation
-(void)viewWillAppear:(BOOL)animated
{
[self createCurrencyArray];
NSUserDefaults *priceDef = [NSUserDefaults standardUserDefaults];
NSString *priceDefText = [priceDef stringForKey:#"priceCall"];
_priceTextField.text = priceDefText;
NSUserDefaults *currencyDef = [NSUserDefaults standardUserDefaults];
[_currencyPicker selectRow:[currencyDef integerForKey:#"currencyCall"]
inComponent:0 animated:NO];
[priceDef synchronize];
[currencyDef synchronize];
}
-(void)viewWillDisappear:(BOOL)animated
{
NSString *textOfPriceTexField = _priceTextField.text;
[[NSUserDefaults standardUserDefaults] setObject:textOfPriceTexField forKey:#"priceCall"];
}
Now, the problem is when I want program to automatically-calculate, it won't. To have any result, I have to switch to Second View, choose a value from picker and then when I will go back, I have my result.
But...
- When I change value on 1st screen, result won't change. When I change value on 2nd scree, result won't change. But when I change value on PickerView - TADAH - result updates!
When I go to second view, and go back to first, then go again to second and go back to first, my result changes to "0.00 (NULL)"...
Any ideas where I did wrong? I think it is about NSUserDefaults, I tried many options, nothing worked, nor changed anything.
You need to synchronize NSUserDefaults when you set new values. You are using synchronize when you retrieve values.
Here you don't need 2 pointers to defaults and don't need synchronize:
NSUserDefaults *priceDef = [NSUserDefaults standardUserDefaults];
NSString *priceDefText = [priceDef stringForKey:#"priceCall"];
_priceTextField.text = priceDefText;
[_currencyPicker selectRow:[priceDef integerForKey:#"currencyCall"] inComponent:0 animated:NO];
Here you need synchronizes:
-(void)viewWillDisappear:(BOOL)animated
{
NSString *textOfPriceTexField = _priceTextField.text;
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:textOfPriceTexField forKey:#"priceCall"];
[defaults synchronize];
}
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
NSInteger selectedRow = [_currencyPicker selectedRowInComponent:0];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setInteger:selectedRow forKey:#"currencyCall"];
[defaults synchronize];
self.currentSettings.currency = [self.currencyArray objectAtIndex:row];
self.currentSettings.price = [self.priceTextField.text floatValue];
//[self userDidFinishSetting];
}
Try this code
-(void)viewWillDisappear:(BOOL)animated
{
NSString *textOfPriceTexField = _priceTextField.text;
[[NSUserDefaults standardUserDefaults] setObject:textOfPriceTexField forKey:#"priceCall"];
}
-(void)viewWillAppear:(BOOL)animated
{
[self createCurrencyArray];
NSUserDefaults *priceDef = [NSUserDefaults standardUserDefaults];
NSString *priceDefText = [priceDef objectForKey:#"priceCall"];
}
instead of stringForKey you can call objectForKey same as for integerForKey also you can call objectForKey. Actually you are setting the object not string or integer.

how to retain my uitextfield values in viewController when i calling?

I have a main page having 3 textfield in my first view as i navigate to different view and return back to my first view (i.e after i enter all the values i moving to next page).I want my 3 textfield to retain its value when i go back to my main page here my sample code :
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *mobile = MobileNum.text;
[defaults setObject:mobile forKey:self.MobileNum.text];
NSString *amountText = amount.text;
[defaults setObject:amountText forKey:self.amount.text];
[defaults synchronize];
NSString *temp = [defaults objectForKey:self.MobileNum.text];
NSString *temp1 = [defaults objectForKey:self.amount.text];
NSLog(#"%# %#",temp,temp1);
at you viewWillDisappear method store the defaults like.
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *mobile = MobileNum.text;
[defaults setObject:mobile forKey:#"mobileNumber"];
NSString *amountText = amount.text;
[defaults setObject:amountText forKey:#"amount"];
[defaults synchronize];
again at your viewWillAppear method retrieve the values like.
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if ([[defaults valueForKey:#"mobileNumber"] length]>0){
MobileNum.text=[defaults valueForKey:#"mobileNumber"];
}
else {
MobileNum.text=#"";
}
if ([[defaults valueForKey:#"amount"] length]>0) {
amount.text=[defaults valueForKey:#"amount"];
}
else {
amount.text=#"";
}
it will work.

How do I make this save button save entered text onto a new page?

- (IBAction)Save:(id)sender {
NSString *saveString = taskName.text;
NSUserDefaults *defults = [NSUserDefaults standardUserDefaults];
[defults setObject:saveString forKey:#"savedString"];
[defults synchronize];
//use data that has been given
}
- (IBAction)theTask:(id)sender {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *loadstring = [defaults objectForKey:#"savedString"];
[taskName setText:loadstring];
[super viewDidLoad];
}
Im trying to attach the new label i made on storyboard to attach to theTask method. So when the user types in a task and pushes save the task is placed in a list of other tasks

Adding to a Previously saved NSUserDefaults

I am making a game for iOS which in includes a scoring system in each level. Here I have some code that gets an NSString (passedValue1) by using a delegate.
Heres the code for the delegate:
LevelCompleteLevel1
.h
#import "ViewController.h"
#interface LevelCompleteLevel1 : UIViewController{
IBOutlet UILabel *label;
ViewController *secondviewData;
}
#property (nonatomic, retain)ViewController*secondviewData;
.m
ViewController *second = [[ViewController alloc] initWithNibName:nil bundle:nil];
self.secondviewData = second;
secondviewData.passedValue1 = label.text;
[self presentModalViewController:second animated:YES];
In the .m I send the a value from a label in the current viewcontroller to another view controller the value I send is called passedValue1
Once I have sent the value I need to display and save in my ViewController
ViewController
.h
#interface ViewController : UIViewController{
IBOutlet UILabel *label;
NSString *passedValue1;
}
#property (nonatomic, retain)NSString *passedValue1;
#end
.m
Firstly I ... #synthesize passedValue1;
Then i add the code to receive the value in my viewDidLoad and display my value in a UILabel
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib
NSString *key=#"labelKey";
// Do any additional setup after loading the view, typically from a nib
if(passedValue1){
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSObject * object = [prefs objectForKey:key];
if(object != nil){
NSUserDefaults *defults = [NSUserDefaults standardUserDefaults];
[defults setObject:passedValue1 forKey:key];
[defults synchronize];
}
else{
NSUserDefaults *defults = [NSUserDefaults standardUserDefaults];
NSInteger readScore=[[[NSUserDefaults standardUserDefaults] objectForKey:key] integerValue];
NSInteger newValue=readScore+[passedValue1 integerValue];
[defults setObject:[NSString stringWithFormat:#"%d",newValue] forKey:key];
[defults synchronize];
}
}
label.text = [[NSUserDefaults standardUserDefaults]objectForKey:key];
}
Once I have displayed the value I then save it into a label using a NSUserDefault. However, once I have replayed my game and have another score value I would like to add the new passedValue1 value to the currently saved value...
For example:
say I play my level and I get the score value of 10. The value is then saved and I replay my level. I would then like to take the saved value and add it to the value i just scored. So thats say the second value I have scored is 20. I would then like my code to add them together and give me a value of 30.
can anyone help because the code I'm using does not correctly do the function that I want to do which is add the previous and the currently passed value.
Thanks in advance.
edit
Iam using this code:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib
NSString *key=#"labelKey";
// Do any additional setup after loading the view, typically from a nib
if(passedValue1){
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSObject * object = [prefs objectForKey:key];
if(object != nil){
NSUserDefaults *defults = [NSUserDefaults standardUserDefaults];
[defults setObject:passedValue1 forKey:key];
[defults synchronize];
}
else{
NSUserDefaults *defults = [NSUserDefaults standardUserDefaults];
NSInteger readScore=[[[NSUserDefaults standardUserDefaults] objectForKey:key] integerValue];
NSInteger newValue=readScore+[passedValue1 integerValue];
[defults setValue:[NSString stringWithFormat:#"%d",newValue] forKey:key];
[defults synchronize];
}
}
label.text = [[NSUserDefaults standardUserDefaults]objectForKey:key];
}
Why is this not working , the displayed value of the label is the originally passedValue1?
once try this one ,
NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
[defaults setObject:#"10" forKey:#"old value"];
[defaults synchronize];
int k=[[defaults objectForKey:#"old value"] intValue]+newValue;
Two things
As you are adding the NSString it is enough to use the setValue: forKey: method. (NOT setObject:forKey as you are using)
NSUserDefaults is a key based value saving mechanism. If you try to save the value in the same key the saved value will be replaced by the current saving value.
So in your case just call for the same key with the new value and you have the older value replaced with new one.

Resources