ios saving and retrieving NSNumber from NSUserdefaults - ios

I've searched but I can't find a good explanation as to why I'm still not getting the right value from my saved Integer.
This is how I saved my event Id.
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setInteger:eventSelected.eventId forKey:#"currentEvent"];
This is how I'm trying to retrieve it.
NSLog(#"user dfault %#", [NSNumber numberWithUnsignedInt:[[[NSUserDefaults standardUserDefaults] objectForKey:#"currentEvent"] unsignedIntegerValue]]);
I'm gettin gthis.
user dfault 123581200
Also, to note, event if I did intValue instead of unsignedIntegerValue , it would still give me a random id number. was wondering what I'm doing wrong.

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
// Convert your value to IntegerValue and Save it
[prefs setInteger:[eventSelected.eventId integerValue] forKey:#"currentEvent"];
// Dont forget to synchronize UserDefaults
[prefs synchronize];
// To Access this value
NSLog(#"%d",[prefs integerForKey:#"currentEvent"]);

Instead of this code NSLog(#"user dfault %#", [NSNumber numberWithUnsignedInt:[[[NSUserDefaults standardUserDefaults] objectForKey:#"currentEvent"] unsignedIntegerValue]]);
Use this
NSLog(#"user dfault %#", [[NSUserDefaults standardUserDefaults] integerForKey:#"currentEvent"]);

NSNumber give a pointer value, not integer value.

To retrieve the integer you should use below function:
[[NSUserDefaults standardUserDefaults] integerForKey:#"currentEvent"];
when you ask for objectForKey, it box it first and then return the object. Posting intValue will convert the address of that object into integer. Hence each time you will receive different number.

NSNumber *number;
store:
[[NSUserDefaults standardUserDefaults] setValue:number forKey:#"Number"];
retrieving:
number = [NSNumber numberWithInteger:[[NSUserDefaults standardUserDefaults] integerForKey:#"Number"]];

Related

How to transfer new int value and save previous int value?

I used
NSString *level =[[NSUserDefaults standardUserDefaults] stringForKey:#"Key"];
But this method may contain only one value.
How to transfer new int value and save previous int value?
A key can only have one value.
If you want to save a previous value, use a new key.
I'd recommend "oldKey" or "previousKey" in your user defaults to indicate the previous value. E.G.:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *oldLevel = [defaults stringForKey: #"Key"];
[defaults setObject: oldLevel forKey: #"PreviousKey"];
[defaults setObject: newLevel forKey: #"Key"];

How would I be able to save an integer when an app is terminated and then load it again once the app is reopened?

I am working on an app where I need to save one int until the player decides to play the game again. It would be greatly appreciated if someone could guide me by using NSUserDefaults to save this integer whenever the application is terminated, and then be able to load it again as soon as the application loads. If there is any further information that is needed to help you help me just let me know! Thanks in advance!
You cannot save an int, you will need to convert it to an NSNumber. Use:
NSNumber *number = #(myInt);
Then you can save it (when the app terminates in your appDelegate's applicationWillTerminate:) using:
[[NSUserDefaults standardUserDefaults] setObject:number forKey:#"number"];
[[NSUserDefaults standardUserDefaults] synchronize];
To retrieve the value use:
NSNumber *number = [[NSUserDefaults standardUserDefaults] stringForKey:#"number"];
As pranav told you can store int as NSNumber or you can store it as a String, Following will work fine with NSNumber object,
int a = 10;
NSNumber *myNumber = [NSNumber numberWithInt:a];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:myNumber forKey:#"storedInt"];
NSLog(#"stored number object %#", [defaults objectForKey:#"storedInt"]); // retrieve value from NSUserDefaults
//then change NSNumber object to int value - if required
int retrievedInt = [myNumber intValue];
NSLog(#"int value %u", retrievedInt);

`NSUserDefaults` not saving float properly

I am building an application in which I want to save some user data by using NSUserDefaults, and it is a property of one of my controllers as following:
#property (nonatomic, strong) NSUserDefaults *userPreference;
#synthesize userPreference = _userPreference;
And I am trying to save something called a scale that should be a float, so I do something like this in the getter to put in some default values of scale in case user did not enter one:
if (!_userPreference) {
_userPreference = [NSUserDefaults standardUserDefaults];
}
if (![_userPreference floatForKey:#"scale"]) {
// if user has not entered this info yet
// also 0 is not a valid value so I can do this
[_userPreference setFloat:100.0 forKey:#"scale"]; // let default scale be 100.0
[_userPreference synchronize];
}
However, when I later on query this, no matter what I set in the default value, the following command:
[self.userPreference floatForKey:#"scale"];
always return 1. I am not sure what is happening. Am I not creating the NSUserDefaults correctly?
Thank you in advance!
if you want to use NSUserDefaults, do not create any variables or #propertys. Just use
[[NSUserDefaults standardUserDefaults] setFloat:forKey:]
[[NSUserDefaults standardUserDefaults] synchronize];
to save your data and
[[NSUserDefaults standardUserDefaults] floatForKey:]
for fetching data.
Store using
[_userPreference setObject:[NSNumber numberWithFloat:100.0] forKey:#"Scale"];
[_userPreference synchronize];
and retrieve it using
float value = [[_userPreference objectForKey:#"Scale"] floatValue];
Have you tried this to set the float value:
[_userPreference setObject:[NSNumber numberWithFloat:100.0f] forKey#"scale"];
and the following to retrieve:
CGFloat scale = [[_userPreference objectForKey#"scale"] floatValue];
Change your if condition to this:
if ([_userPreference floatForKey:#"scale"] == 0.0f ) {
NSUserDefaults will always return 0.0f if no value is set for the key. Since you are saying that "also 0 is not a valid", you can safely use this approach
try this
-(void) saveFloatToUserDefaults:(float)x forKey:(NSString *)key {
NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setFloat:x forKey:key];
[userDefaults synchronize];
}
-(float) retriveFromUserDefaultsForKey:(NSString *)key {
NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults];
return [userDefaults floatForKey:key];
}
[self saveFloatToUserDefaults:6.55 forKey:#"myFloat"];
float x = [self retriveFromUserDefaultsForKey:#"myFloat"];

How to set initial values for NSUserDefault Keys?

I want to set some initial values for my NSUserDefault keys so that the first run of the app has some reasonable initial settings. I thought I ran across a simple way to do this in the app bundle .plist, but now I can't find it. Any ideas?
You should use the registerDefaults method of NSUserDefaults. Prepare a plist file in your bundle that contains the default preferences and then use that plist to register the defaults.
NSString *defaultPrefsFile = [[NSBundle mainBundle] pathForResource:#"defaultPrefs" ofType:#"plist"];
NSDictionary *defaultPreferences = [NSDictionary dictionaryWithContentsOfFile:defaultPrefsFile];
[[NSUserDefaults standardUserDefaults] registerDefaults:defaultPreferences];
You have to execute this code on every launch of your app. It will add these values to a separate domain in the user defaults hierarchy. Whenever your app's user defaults don't provide a value for a certain key, NSUserDefaults will fall back to this domain and retrieve the value from there.
If you have many default values, let use ola's answer, otherwise this is good for a few params
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if (![defaults boolForKey:USERDEFAULT_IS_INITIALIZED]) {
[defaults setBool:YES forKey:USERDEFAULT_IS_INITIALIZED];
// Set initial values
...
[defaults synchronize];
}
if ([[[[NSUserDefaults standardUserDefaults] dictionaryRepresentation] allKeys] containsObject:#"initialValuesHaveBeenWritten"])
{
[[NSUserDefaults standardUserDefaults] setValue:obj1 forKey:key1];
[[NSUserDefaults standardUserDefaults] setValue:obj2 forKey:key2];
[[NSUserDefaults standardUserDefaults] setValue:obj1 forKey:#"initialValuesHaveBeenWritten"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
NB: Not tested, done from memory
-(void) loadDef
{
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
_removeAd=[userDefaults boolForKey:SAVE_AD_STATUS];
NSString* strDefSetting=[userDefaults stringForKey:SAVE_STATUS_ADSETTING];
if(strDefSetting==nil
||[strDefSetting isEqualToString:#""]
)
{
strDefSetting=#"0.5";
}
_floatAdmob=strDefSetting.floatValue;//0.5;
}

How would I save a UIButton's properties and load with a button? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How can I save and load the alpha values of a UIButton in an app?
I would like to save the state of the UIButton (e.g. its alpha value and whether it is hidden or not) and this would then load up when the user quits and reloads the app.
I've tried some bits of code with NSUserDefaults but with no luck.
Could somebody help with some sample code so that I can save and load the button's state?
Thanks,
James
Related to Shaharyar's answer (i don't know how to comment):
in this case you need to use NSNumber.
[[NSUserDefaults standardUserDefaults] setValue:[NSNumber numberWithFloat:SOME_FLOAT] forKey:KEY];
because float is not an object, but NSNumber is one.
EDITED:
1) To make sure your defaults are created after the application runs at first time:
in your AppDelegate's initialize-method:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSDictionary *appDefaults = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithFloat:SOME_FLOAT], #"YOUR_KEY",
nil];
[defaults registerDefaults:appDefaults];
2) Updating defaults after:
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setFloat:FLOAT_VALUE forKey:#"YOUR_KEY"];
[prefs synchronize];
3) Read defaults:
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
float FLOAT_VALUE = [prefs floatForKey:#"YOUR_KEY"];
Can you post some of the code?
NSUserDefaults is the place to store such information..
Assumption:
Did you make a call to [NSUserDefaults synchronize] after setting the values?
Code:
// Setting a value
[[NSUserDefaults standardUserDefaults] setValue:VALUE forKey:KEY];
[[NSUserDefaults standardUserDefaults] synchronize];
// Getting a value
NSString *var1 = [[NSUserDefaults standardUserDefaults] valueForKey:KEY];
In your case it would be:
// Setting a value
[[NSUserDefaults standardUserDefaults] setFloat:VALUE forKey:KEY];
[[NSUserDefaults standardUserDefaults] synchronize];

Resources