IPhone SDK Default NSUserDefaults - iphone

I have set up the user defaults to record a integer for a UISlider, the problem is that, if the user has only just installed the app then the integer is zero or NULL. Is there a way to detect if it = NULL with a integer?
heres my code i have so far:
-(void)awakeFromNib {
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
senset = [prefs integerForKey:#"senset"];
senset = sensitivity.value;
}
- (IBAction) setSens {
senset = sensitivity.value;
}
- (IBAction) goBackopt {
{
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setInteger:senset forKey:#"senset"];
[prefs synchronize];
}
}
senset is the integer. i have tried this code, and it sets it to 25 on the first time, but then if i try and overwrite it, it wont work and keeps setting it to 25. :(
if ( [prefs integerForKey:#"senset"] == NULL ) {
senset = 25;
}
Please help :P
Harry

You should set a valid default value for each of your preferences. This value will be used when one has not been set by the user.
NSMutableDictionary *defaults = [NSMutableDictionary dictionary];
[defaults setObject:[NSNumber numberWithInt:25] forKey:#"senset"];
[[NSUserDefaults standardUserDefaults] registerDefaults:defaults];

Just ask for objectForKey:. If it isn't set, it will return nil.
Your test doesn't work, because integerForKey: with an unset value will return 0, which is nil, which is NULL. The differences between them only exist to the compiler.

If zero is not a valid value in a normal usage case (i.e. your saved preference would never set this integer to zero), then you can check
if( [prefs integerForKey:#"senset"] == 0){
[prefs setInteger:25 forKey:#"senset"];
}
Edit: err, I suppose I have a question: when you try to overwrite it, are you setting an integer value(25) for your key (#"senset")? If not, then it will remain zero or nil, and everytime you check it will attempt to change your local senset variable to 25 again.

Related

what is the use of standardUserDefaults?

I am new in iphone programming. please explain me this code. and that is the use of standardUserDefaults? how this code will work?
-(void)load
{
DLog("Load Configuration");
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
bool savedDefaults = [defaults boolForKey:kKeySavedDefaults];
if (savedDefaults)
{
columns = [defaults integerForKey:kKeyColumns];
if (columns == 0) columns = kColumnsDefault;
rows = [defaults integerForKey:kKeyRows];
if (rows == 0) rows = kRowsDefault;
photoType = [defaults integerForKey:kKeylastPhotoType];
photoEnabled = [defaults boolForKey:kKeyPhotoEnabled];
numbersEnabled = [defaults boolForKey:kKeyNumbersEnabled];
soundEnabled = [defaults boolForKey:kKeySoundEnabled];
}
else
{
columns = kColumnsDefault;
rows = kRowsDefault;
photoType = klastPhotoTypeDefault;
photoEnabled = kPhotoEnabledDefault;
numbersEnabled = kNumbersEnabledDefault;
soundEnabled = kSoundEnabledDefault;
}
}
-(void)save
{
DLog("Save Configuration");
BOOL restart = NO;
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if ([defaults integerForKey:kKeyColumns] != columns) { restart = YES; }
if ([defaults integerForKey:kKeyRows] != rows) { restart = YES; }
[defaults setBool:YES forKey:kKeySavedDefaults];
[defaults setInteger:columns forKey:kKeyColumns];
[defaults setInteger:rows forKey:kKeyRows];
[defaults setInteger:photoType forKey:kKeylastPhotoType];
[defaults setBool:photoEnabled forKey:kKeyPhotoEnabled];
[defaults setBool:numbersEnabled forKey:kKeyNumbersEnabled];
[defaults setBool:soundEnabled forKey:kKeySoundEnabled];
[defaults synchronize];
[board configChanged:restart];
}
User defaults are used to store little configuration parameters.
From the documentation :
The NSUserDefaults class provides a programmatic interface for
interacting with the defaults system. The defaults system allows an
application to customize its behavior to match a user’s preferences.
For example, you can allow users to determine what units of
measurement your application displays or how often documents are
automatically saved. Applications record such preferences by assigning
values to a set of parameters in a user’s defaults database. The
parameters are referred to as defaults since they’re commonly used to
determine an application’s default state at startup or the way it acts
by default.
If you want to store some small amount of data like username,password...... by using these concept you can store the values

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

How to store a float in NSUserDefaults

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"]);
}

should variable be released or not? iphone-sdk

I have the following piece of code from a book.
There is this function loadPrefs where the NSString *userTimeZone is being released before the end of the function.
Why? The string was not created with alloc and I assume that the stringForKey function returns an autoreleased NSString. Is this an error or am I missing something? Is it an error in the book? (I new into objective-C)
In the documentation for stringForKey the only thing it mentions is:
Special Considerations
The returned
string is immutable, even if the value
you originally set was a mutable
string.
The code:
- (void) loadPrefs {
timeZoneName = DefaultTimeZonePref;
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *userTimeZone = [defaults stringForKey: TimeZonePrefKey];
if (userTimeZone != NULL)
timeZoneName = userTimeZone;
[userTimeZone release];
show24Hour = [defaults boolForKey:TwentyFourHourPrefKey];
}
Thanks!!!!
You're right. There are two things wrong with this code: it's releasing the string from stringForKey: improperly, and it's not retaining userTimeZone when it assigns the value to an instance variable.
Here's a better attempt:
- (void) loadPrefs {
[timeZoneName release]; // In case there was a previous value
timeZoneName = DefaultTimeZonePref; // ASSUMPTION: DefaultTimeZonePref is a constant
// And thus doesn't need retain/release.
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *userTimeZone = [defaults stringForKey: TimeZonePrefKey];
if (userTimeZone != NULL) {
timeZoneName = [userTimeZone retain];
}
show24Hour = [defaults boolForKey:TwentyFourHourPrefKey];
}
And don't forget to release timeZoneName in dealloc.

Iphone SDK how to save my score?

i have a integer called HighScore which is connected to highscorelabel . i have made it so when the user gets a high score it puts the score they got onto the label but i would now like to know how i can save it so that when the app is opened again it will still have the high score : this is my code for detecting when a high score is made
(void) submitScore {
if (lives > HighScore){
HighScore = lives;
}
highscorelabel.text = [NSString stringWithFormat:#"%i" , HighScore];
}
Use NSUserDefaults for saving:
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setInteger:HighScore forKey:#"HighScore "];
[prefs synchronize];
and retrieving:
HighScore = [prefs integerForKey:#"HighScore"];