How to store a float in NSUserDefaults - iphone

I want to store a float value into NSUserDefaults.
I also need to check that the float value exists..if not I need to assign some value in it.
and retrieve it...for the above I have the below code but it gives me an error.
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if ([defaults boolForKey:#"HANDWRITING_SIZE_SLIDER"] == YES) {
self.sizeSlider.value = 10.0;
} else {
self.sizeSlider.value = [[NSUserDefaults standardUserDefaults] floatForKey:#"HANDWRITING_SIZE_SLIDER"]];
}
Thanks for any help

Use the NSNumber class for this and store it via the setObject:forKey: method so you can check if it exists.
I'd also suggest the usage of constants as keys:
#define HANDWRITING_SIZE_SLIDER #"HSS"
Your code should be along these lines:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if ([defaults objectForKey:HANDWRITING_SIZE_SLIDER] == nil) {
//doesn't exist in NSUserDefaults, set to default value...
self.sizeSlider.value = 10.0;
} else {
self.sizeSlider.value = [[defaults objectForKey:HANDWRITING_SIZE_SLIDER] floatValue];
}
Somewhere else in your app, you'd set the value in NSUserDefaults like this:
float sizeSliderValue = ...
[[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithFloat:sizeSliderValue] forKey:HANDWRITING_SIZE_SLIDER];

Try this code:
-(IBAction)sliderAction:(id)sender
{
float sliderValue = [sender floatValue];
[[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithFloat:sliderValue] forKey:#"keySliderValue"];
NSLog(#"%#",[[NSUserDefaults standardUserDefaults] objectForKey:#"keySliderValue"]);
}

Related

NSUserDefaults in NSMutableArray

How to set/make this into an NSMutableArray?
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setInteger:1 forKey:#"KeyI1"];
[prefs setInteger:1 forKey:#"KeyJ1"];
[prefs setInteger:1 forKey:#"KeyI2"];
[prefs setInteger:1 forKey:#"KeyJ2"];
Which I can use for an if statement something like this:
NSInteger I1=[prefs integerForKey:#"KeyI1"];
NSInteger I2=[prefs integerForKey:#"KeyI2"]
NSInteger J1=[prefs integerForKey:#"KeyJ1"]
NSInteger J2=[prefs integerForKey:#"KeyJ2"]
if ( I1 == index1 && K1 == index2){
}
if ( I2 == index1 && K2 == index2){
}
You can't use setInteger: for NSUserDefaults (which uses a NSMutableDictionary structure) directly. You should use setObject:forKey: and objectForKey: and add your integers in NSNumber objects or write a NSMutableDictionary category that will handle setInteger:forKey: and integerForKey:.

find special keys in UserDefaults by "substringToIndex"

I'm grouping my UserDefault keys by specific prefixes.
e.g.
[NSUserDefaults standardUserDefaults] setInteger: 1 forKey: #"prefix1_someText_Key"]
[NSUserDefaults standardUserDefaults] setInteger: 2 forKey: #"prefix2_someText_Key"]
[NSUserDefaults standardUserDefaults] setInteger: 3 forKey: #"prefix4_someText_Key"]
//.....
Now, I'd like to find all the keys, that start with e.g. "prefix", and load them into an array. is there a way for doing that (programmatically)?
You could use the underlying NSDictionary to find the suitable keys:
NSString *myPrefix = #"prefix";
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSDictionary *dict = [defaults dictionaryRepresentation];
NSMutableArray *keysWithPrefix = [NSMutableArray array]
for (NSString *key in dict.keyEnumerator) {
if ([key hasPrefix: myPrefix]) {
[keysWithPrefix addObject: key];
}
}
// now keysWithPrefix contains all matching keys
UPDATE
For debugging reasons you could add a log to see what keys are being dropped:
for (NSString *key in dict.keyEnumerator) {
if ([key hasPrefix: myPrefix]) {
[keysWithPrefix addObject: key];
} else {
NSLog(#"Dropping key %#", key);
}
}

iPhone: preserve NSUserDefaults values when application is killed

I am trying to implement "Add to Favorites" functionality using NSUserDefaults. So far I have written following code.
- (void)favouriteButtonClicked:(id)sender
{
favselected = !favselected; // favselected is BOOL property
MyAppDelegate *appDelegate = (MyAppDelegate *)[[UIApplication sharedApplication] delegate];
NSString* viewname = #"custom";
if(favselected) {
[favButton setBackgroundImage:[UIImage imageNamed:#"selected.png"] forState:UIControlStateNormal];
[appDelegate addTOFavourites:self.ViewID viewType:self.ViewType];
} else {
[favButton setBackgroundImage:[UIImage imageNamed:#"unselected.png"] forState:UIControlStateNormal];
[appDelegate removeFromFavourites:self.ViewID viewType:self.ViewType];
}
}
It is working fine as long as my application is running but when I killed my application, I am losing all my stored values so when next time view loaded, in viewload isAddedToFavorites method returns false. Is there anyway to preserve my values? Am I missing something?
if([appDelegate isAddedToFavorites:self.ViewID]) {
[favButton setBackgroundImage:[UIImage imageNamed:#"selected.png"] forState:UIControlStateNormal];
favselected = YES;
} else {
[favButton setBackgroundImage:[UIImage imageNamed:#"unselected.png"] forState:UIControlStateNormal];
favselected = NO;
}
Edit:
I tried using NSMutableDictionary as I have to add multiple key-values but following method always display Count=0 even after adding object to dictionary. Any help would be really appreciated. Thank you.
-(BOOL)isAddedToFavorites:(NSString*)viewID {
NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
NSMutableDictionary *favourites = [[standardUserDefaults objectForKey:kFavouriteItemsKey] mutableCopy];
if(favourites && [[favourites objectForKey:kFavouriteItemsKey] objectForKey:viewID])
return YES;
return NO;
}
-(void)addToFavourites:(NSString*)viewID viewType:(NSString*)viewType {
NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
NSMutableDictionary *dict = [[standardUserDefaults objectForKey:kFavouriteItemsKey] mutableCopy];
if(standardUserDefaults) {
if(![dict objectForKey:viewID])
[dict setObject:viewType forKey:viewID]; // It is coming here but still count zero!
NSLog(#"count = %d", [dict count]);
[standardUserDefaults setObject:dict forKey:kFavouriteItemsKey]; // Always dict remains null with 0 objects in it
[standardUserDefaults synchronize];
[dict release];
}
}
-(void)removeFromFavourites:(NSString*)viewID viewType:(NSString*)viewType {
NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
NSMutableDictionary *dict = [[standardUserDefaults objectForKey:kFavouriteItemsKey] mutableCopy];
if(standardUserDefaults) {
if ([dict objectForKey:viewID])
[dict removeObjectForKey:viewID];
[standardUserDefaults setObject:dict forKey:kFavouriteItemsKey];
[standardUserDefaults synchronize];
[dict release];
}
}
Thanks.
NSUserDefaults is actually used to store values permanently, in fact if you create any Settings for your program they will be saved as NSUserDefaults.
I think the problem is that you are not saving it with the same key you are retrieving. Try saving like this:
//To save
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:appDefaults forKey:kFavouriteItemsKey];
[[NSUserDefaults standardUserDefaults] synchronize];
//To retrieve
NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
NSMutableDictionary *favourites = [[standardUserDefaults objectForKey:kFavouriteItemsKey] mutableCopy];
For the dictionary try:
NSDictionary *myDictionary= [[NSUserDefaults standardUserDefaults] objectForKey:kFavouriteItemsKey];
// Create a mutable dictionary to replace the old immutable dictionary
NSMutableDictionary *myMutableDictionary= [NSMutableDictionary dictionaryWithCapacity:[myDictionary count]+1];
// transfer the old dictionary into the new dictionary
[myMutableDictionaryaddEntriesFromDictionary:myDictionary];
// Now add the data
[myMutableDictionary setObject:myObject forKey:myKey];

Having an NSUserDefault Problem

I am trying to save a couple of preferences in a program I can't seem to make NSUserDefaults work properly. If someone could take a look at my code and see if there are any errors it would be appreciated
NSString *kGameIsPaused = #"gameGameIsPaused";
NSString *kSoundOn = #"gameSoundOn";
NSString *kMusicOn = #"gameMusicOn";
NSString *kHighScore = #"gameHighScore";
- (void)saveGameState
{
[[NSUserDefaults standardUserDefaults] setBool:gameIsPaused forKey:kGameIsPaused];
[[NSUserDefaults standardUserDefaults] setBool:soundOn forKey:kSoundOn];
[[NSUserDefaults standardUserDefaults] setBool:musicOn forKey:kMusicOn];
[[NSUserDefaults standardUserDefaults] setInteger:highScore forKey:kHighScore];
}
-(void)loadGameState
{
gameIsPaused = [[NSUserDefaults standardUserDefaults] boolForKey:kGameIsPaused];
soundOn = [[NSUserDefaults standardUserDefaults] boolForKey:kSoundOn];
musicOn = [[NSUserDefaults standardUserDefaults] boolForKey:kMusicOn];
highScore= [[NSUserDefaults standardUserDefaults] integerForKey:kHighScore];
if (soundOn == NO) {
[soundToggle setImage:[UIImage imageNamed:#"SoundOFF.png"] forState:UIControlStateNormal];
}
if (musicOn == NO) {
[musicToggle setImage:[UIImage imageNamed:#"MusicOff.png"] forState:UIControlStateNormal];
}
}
they everytime i run the loadGameState method I get returned the default values as if there is no key to reference.
Inside of saveGameState I would recommend adding a synchronize to your defaults to persist them. If your game is crashing or you are stopping the debugger or anything else goes wrong they may not get saved properly.
- (void)saveGameState
{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setBool:gameIsPaused forKey:kGameIsPaused];
[defaults setBool:soundOn forKey:kSoundOn];
[defaults setBool:musicOn forKey:kMusicOn];
[defaults setInteger:highScore forKey:kHighScore];
[defaults synchronize];
}

How do I save a UISlider value?

How could I save the value of a UISlider ?I tried this, but it didn't work:
-(IBAction)save {
slider1i = slider1.value;
NSUserDefaults *slider1save = [NSUserDefaults standardUserDefaults];
[slider1save setInteger:slider1i forKey:#"slider1key"];
[slider1save synchronize];
}
slider1i is a NSinteger, and slider1 is the UISlider ...
Can you help-me ?
As user 698952 said, UISlider's value property is a float. But i'd instead use setFloat like this:
slider1i = slider1.value;
NSUserDefaults *slider1save = [NSUserDefaults standardUserDefaults];
[slider1save setFloat:slider1i forKey:#"slider1key"];
[slider1save synchronize];
slider1.valueis float value so you first need to convert it in NSString or NSNumber inorder to save it ..... that makes it a object
-(IBAction)save {
NSNumber *sliderValue = [NSNumber numberWithFloat:slider1.value];
NSUserDefaults *slider1save = [NSUserDefaults standardUserDefaults];
[slider1save setObject:sliderValue forKey:#"slider1key"];
[slider1save synchronize];
}
thanks