Save value of the variable - ios7

Here is the NSUserdefaults code.
-(IBAction)SaveButton:(id)sender {
NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
NSString* Assignment0Text = screen0.text;
[defaults setObject:Assignment0Text forKey:#"Assignment0Text"];
[defaults synchronize];
}
-(IBAction)LoadButton:(id)sender {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString* temp0 = [defaults objectForKey:#"Assignment0Text"];
screen0.text = temp0;
}
This code above means that the program only saves and loads the string value inside the textfield/label.
My question is, how can I modify this code so that the NSUserDefaults can save and load the value of a variable (in this case int & float), not the text inside the textfield/label? So that when I load the program, all the integer/float values are the same. Not what's written in the text inside the textfield/label are the same. All that the screen is showing is a float number with variable called runningtotal.
screen0.text = [NSString stringWithFormat:#"%2.2f", runningtotal];

if I understand your question correctly, you should use wrappers for variables like int:
int value = 5;
[defaults setObject:#(value) forKey:#"Assignment0Number"];
the magic is the NSUserDefaults can not store non-object values like 5. You need to create NSObject object, store the value within it, and then save this object into the NSUserdefaults. That is what happens when I write '#(value)'.
If to be more precise, #(value) is literal for [NSNumber numberWithInt:value], and since NSNumber is the object and subclass of NSObject, the value can be stored now.
EDIT:
here is what you probably want (I assume that runningtotal is the class variable):
-(IBAction)SaveButton:(id)sender {
NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
[defaults setObject:#(runningtotal) forKey:#"Assignment0Text"];
[defaults synchronize];
}
-(IBAction)LoadButton:(id)sender {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSNumber* temp0 = [defaults objectForKey:#"Assignment0Text"];
runningtotal = [temp0 intValue];
}

Related

How to load the user’s last selected value for a slider when the app relaunches?

I am new to Xcode and I am using Objective C in OSX.
I am trying to load the user’s last selected value for a slider when the app relaunches.
my code for the slider is…
- (IBAction)sliderChanged:(id)sender {
amount = [self.amountSlider integerValue];
NSString *amountString = [NSString stringWithFormat:#"%ld", amount];
[self.amountLabel setStringValue:amountString];
}
I have this setter…
- (void)setInteger:(NSInteger)valueforKey:(NSString *)defaultName{
[[NSUserDefaults standardUserDefaults] setObject:#"amountString" forKey:#"amountSlider"];
}
I would like to know how to code the getter.
A step-by-step instructions with code will be appreciated.
Any improvements/corrections to my existing code above would also be appreciated.
Make separate functions for retrieving, saving from defaults like this.
- (void)saveValueToUserDefaults:(NSString *)pValue key:(NSString *)kKey {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[self removeValueFromUserDefaults:kKey];
[defaults setObject:pValue forKey:kKey];
[defaults synchronize];
}
- (void)removeValueFromUserDefaults:(NSString *)kKey {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if ([defaults objectForKey:kKey]) {
[defaults removeObjectForKey:kKey];
}
}
- (NSString *)retriveValueFromUserDefaults:(NSString *)kKey {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if ([defaults objectForKey:kKey]) {
return [defaults objectForKey:kKey];
} else {
return kStringEmpty;
}
}
This will make simple to save and retrieve values from defaults.
Like-
[self saveValueToUserDefaults:YOUR_AMOUNT forKey:YOUR_KEY];
and get like this,
YOUR_AMOUNT = [self retriveValueFromUserDefaults:YOUR_KEY];
You asked for it :D
in your class create integer variable called amountChecker = 0
create a function called checker like this :
-(void) checker {
if (amount == amountChecker){
[[NSUserDefaults standardUserDefaults] setObject:amountLabel.text forKey:#"amountSlider"];
}
else
amount = amountChecker;
}
then .. in this function :
- (IBAction)sliderChanged:(id)sender {
amount = [self.amountSlider integerValue];
NSString *amountString = [NSString stringWithFormat:#"%ld", amount];
[self.amountLabel setStringValue:amountString];
[self performSelector:#selector(checker) withObject:nil afterDelay:1];
}
now this code will only store your value if a second passes and your slider didn't change , instead of storing your value like 60 times every second :D
it all starts when you change the slider then after one second it will check if the value changed if not it will store it
and when you reopen the app you will use this code :
amount = [[NSUserDefaults standardUserDefaults] objectForKey:#"amountSlider"];

NSUserDefaults Arrays

I need two NSMutableArray that will contain NSString.
These arrays are:
ListOFUserNames=[NSMutableArray array];
SituationstoName =[NSMutableArray array];
I have two different sets of strings that go into each mutable array.
After named gets added to Listofusernames
Situation gets added to SituationstoName
[ListOFUserNames addObject:AfterNamed];
[SituationstoName addObject:Situation];
I am trying to save listofusernames and situationstoname with their respective strings.
NSUserDefaults *something = [NSUserDefaults standardUserDefaults];
[something setObject:ListOFUserNames forKey:#"somedata"];
[something synchronize];
NSUserDefaults *something2 = [NSUserDefaults standardUserDefaults];
[something2 setObject:SituationstoName forKey:#"somedata2"];
[something2 synchronize];
In the method that loads them, nothing comes out.
The code for that method is:
NSUserDefaults *somet = [NSUserDefaults standardUserDefaults];
NSUserDefaults *somet2 = [NSUserDefaults standardUserDefaults];
ListOFUserNames = [somet objectForKey:#"somedata"] ;
SituationstoName = [somet2 objectForKey:#"somedata2"] ;
[somet synchronize];
[somet2 synchronize];
The problem is that it is not loading the strings that are saved in the mutable arrays.
//initialise array
NSMutableArray *listOFUserNames=[[NSMutableArray alloc] init];
NSMutableArray *situationstoName =[[NSMutableArray alloc] init];
//add content in the array
[listOFUserNames addObject:AfterNamed];
[situationstoName addObject:Situation];
(Before storing also check if your array contains objects or is empty.)
//Store these array in `NSUserDefaults`
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setObject:listOFUserNames forKey:#"NameData"];
[userDefaults setObject:situationstoName forKey:#"SituationData"];
[userDefaults synchronize];
//Access data where ever you want to be
//(listOFUserNames and situationstoName must be array)
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
listOFUserNames = [userDefaults objectForKey:#"NameData"] ;
situationstoName = [userDefaults objectForKey:#"SituationData"] ;

If statement in NSUserDefault when loading a string

I have the following code for saving a value and an string. I want to use If statement to check my value.
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:#"Baseball bat" forKey:#"Weaponsname"];
NSInteger Attack1 = [defaults integerForKey:#"Attack"];
NSString *Weapon = [defaults stringForKey:#"Weaponsname"];
if([Weapon isEqual: #"Baseball bat"]){
[defaults setInteger:(Attack1+50) forKey:#"Attack"];
NSLog(#"Baseball bat");
}
[defaults synchronize];
So if i have the Baseball bat, the Attack should increase by 50. But it doesn't.
What wrong with the code?
Thanks
For string comparison you should use the isEqualToString method found in the NSString class.
if ([Weapon isEqualToString:#"Baseball bat"]) { ... }

NSUserDefaults Reset First Run

I have an app already in the AppStore that uses NSUserDefaults. Some of the defaults are Default settings that I go ahead and set when the app is first launched, and then the user is allowed to change them later if they wish. So, in my AppDelegate appDidFinishLaunchingWithOptions I put:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if (! [defaults boolForKey:#"notFirstRun"]) {
[defaults setBool:YES forKey:#"notFirstRun"];
[defaults setInteger:0 forKey:#"verseKey"];
[defaults synchronize];
}
The issue I am having now is I want to add some more Default settings in the NSUserDefault category, so I want to make it look like this:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if (! [defaults boolForKey:#"notFirstRun"]) {
[defaults setBool:YES forKey:#"notFirstRun"];
NSString *smalltitle = #"4";
NSString *smallarticle = #"3";
[defaults setObject:smalltitle forKey:#"Title"];
[defaults setObject:smallarticle forKey:#"Article"];
[defaults setInteger:0 forKey:#"verseKey"];
[defaults synchronize];
}
I know that this will cause an issue for those who have already downloaded the app, and are merely updating it. They will not run that code because the notFirstRun Bool has already been set to YES. Any thoughts on what I should do here?
The proper solution is to not actually populate NSUserDefaults with default values. Instead, use the registerDefaults: method.
At app startup you do:
NSUserDefaults *default = [NSUserDefaults standardUserDefaults];
[defaults registerDefaults:#{
#"Title" : #"4",
#"Article" : #"3",
#"verseKey" : #0
}];
That's it. Call this every time the app is run. These defaults are not actually persisted. The value is only returned if there isn't already an explicit value for the key. You can update these defaults all you want without affecting any existing values.
Make a new notFirstRun Boolean value (i.e. notFirstRunTwo). That will be 'NO' for existing users, too.
I suggest to do the following :
check userdefaults for stored app version if it is equal to the current or not , if not.
store the current app version and do your first launch initialization
the code
`
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *appVersion = [NSString stringWithFormat:#"%#",[[NSBundle mainBundle] objectForInfoDictionaryKey:#"CFBundleShortVersionString"]];
if (! [defaults objectForKey:appVersion ])
{
/// store the current version and then do your first run functions
[defaults setObject:[NSNumber numberWithInt:1] forKey:appVersion];
/// here do your first run
......
}`

passing a variable declared in one class to another class

I was trying to set a number in a textfield in one view, that is controlled by one class and make this number appear in a label that is in another view controlled by other class, how do i do it??
Very simple way is NSUserDefault. I don't recommend this but this a way to get data
Saving
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
// saving an NSString
[prefs setObject:#"TextToSave" forKey:#"keyToLookupString"];
// saving an NSInteger
[prefs setInteger:42 forKey:#"integerKey"];
// saving a Double
[prefs setDouble:3.1415 forKey:#"doubleKey"];
// saving a Float
[prefs setFloat:1.2345678 forKey:#"floatKey"];
// This is suggested to synch prefs, but is not needed (I didn't put it in my tut)
[prefs synchronize];
Retrieving
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
// getting an NSString
NSString *myString = [prefs stringForKey:#"keyToLookupString"];
// getting an NSInteger
NSInteger myInt = [prefs integerForKey:#"integerKey"];
// getting an Float
float myFloat = [prefs floatForKey:#"floatKey"];
multiple repost like :
How can I pass a parameter into a view in iOS?
iphone Pass String to another .m file in project
you can also looks segue and protocol delegate