how to save switch state with user defaults? - iphone

Is there a method to store the state of a UISwitch with NSUserDefaults?
If the state is ON I'd like to set some action...
Can I do this?
Thanks!

The answer of hotpaw2 is good and can also work well for big segmented control (more than 2 states). But if you only want to store 2 states, why not just use [setBool:forKey:] like this
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setBool:switchState forKey:#"mySwitchValueKey"];
and get it out:
BOOL swichState = [userDefaults boolForKey:#"mySwitchValueKey"];
which imo, is much much simpler, no if else code at all, no string converting back and for

To save:
- (void)mySwitchAction:(id)sender
{
if (sender == mySwitch) {
BOOL mySwitchValue = [ sender isOn ];
NSString *tmpString = mySwitchValue ? #"1" : #"-1" ;
NSUserDefaults *myNSUD = [NSUserDefaults standardUserDefaults];
[ myNSUD setObject:tmpString forKey: #"mySwitchValueKey" ];
[ myNSUD synchronize ];
// do other stuff/actions
}
}
To initialize from saved state:
NSUserDefaults *myNSUD = [NSUserDefaults standardUserDefaults];
NSString *tmpString = [ myNSUD stringForKey: #"mySwitchValueKey"];
BOOL mySwitchValue = NO; // or DEFAULT_VALUE
if (tmpString != nil) {
mySwitchValue = ( [ tmpString intValue ] == 1 );
}
[mySwitch setOn: mySwitchValue];

Related

How to save UISwitch state on plist file?

i am trying to save the state of UISwitch .If the UISwitch state is "ON" and when the user quits the app and starts it again ..the app should show the previous state and if the user plans to change the state of UISwitch to "OFF"..he should get a message saying previously he had "ON" state and change to state to "OFF"
if you guys help me out that would be great .Thanks
-(IBAction)notification:(id)sender
{
if (sender == notifyMe)
{
if(notifyMe.isOn == YES)
{
toggle = YES;
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
[defaults setBool:notifyMe.on forKey:#"switchValueKey"];
[defaults synchronize];
NSLog(#"Notification is ON");
}
else
{
toggle = NO;
NSLog(#"Notification is OFF");
}
}
if ([cellDelegate respondsToSelector:#selector(notificationReqd:)])
{
[cellDelegate notificationReqd:self];
}
}
Change your button action method like:
-(IBAction)notification:(id)sender
{
if (sender == notifyMe)
{
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
BOOL previousState = [defaults boolForKey:#"switchValueKey"];
if(notifyMe.isOn == YES)
{
toggle = YES;
NSLog(#"Notification is ON");
}
else
{
toggle = NO;
NSLog(#"Notification is OFF");
}
[defaults setBool:toggle forKey:#"switchValueKey"];
[defaults synchronize];
//You can show the message here
NSLog(#"Previous state was %d",previousState);
}
if ([cellDelegate respondsToSelector:#selector(notificationReqd:)])
{
[cellDelegate notificationReqd:self];
}
}
When you want to get the stored data you can use:
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
BOOL previousState = [defaults boolForKey:#"switchValueKey"];

NSMutableArray in NSUserDefaults

I'm sorry for my bad english but i'm trying to explain with best words.
I have some problem when i'm trying to insert an NSMutableArray in NSUserDefaults ([NSUserDefaults setObject:forKey:]: Attempt to insert non-property value ')
My code to insert the array is as follows:
-(void)saveToUserDefaults:(NSMutableArray*)myArray
{
NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
NSArray *array = [[NSArray alloc ] initWithArray:myArray];
if (standardUserDefaults)
{
[standardUserDefaults setObject:array forKey:#"MyArray"];
[standardUserDefaults synchronize];
}
}
My code to retrieve the array:
-(NSMutableArray*)retrieveFromUserDefaults
{
NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
NSMutableArray *val = [[NSMutableArray alloc]init];
if (standardUserDefaults)
val = [NSMutableArray arrayWithArray:[standardUserDefaults arrayForKey:#"MyArray"]];
return val;
}
and in my code :
NSMutableArray :
series = [[NSMutableArray alloc]initWithObjects:nil];
//add some object inf my array...
Save my NSMutableArray :
[self saveToUserDefaults:series];
Retrieve my NSMutableArray :
series = [self retrieveFromUserDefaults];
I think it's not the best way to do this, so if anyone have ideas , it'll be helpful for me.
Thanks for reading.
Tommy
Only immutable NSArrays can be placed into defaults. Rather than placing a NSMutableArray there, convert to regular array using [NSArray arrayWithArray:] and place that one into defaults.
For retrieval, retrieve an NSArray and then use [NSMutableArray arrayWithArray:].
You can use following method to get the mutable object from immutable. It's not optimized and only implemented for NSArray and NSDictionary.
+ (id) GetMutable:(id)input {
id result;
if ([input superclass] == [NSArray class] || [input superclass] == [NSMutableArray class]) {
result = [[NSMutableArray alloc] initWithArray:input copyItems:YES];
for (int i = 0; i < [(NSMutableArray*)result count]; i++) {
[(NSMutableArray*)result replaceObjectAtIndex:i withObject:[Globals GetMutable:[(NSMutableArray*)result objectAtIndex:i]]];
}
} else if ([input superclass] == [NSDictionary class] || [input superclass] == [NSMutableDictionary class]) {
result = [[NSMutableDictionary alloc] initWithDictionary:input copyItems:YES];
NSArray *keys=[(NSMutableDictionary*)result allKeys];
for (int i = 0; i < keys.count; i++) {
[(NSMutableDictionary*)result setObject:[Globals GetMutable:[(NSMutableDictionary*)result objectForKey:[keys objectAtIndex:i]]] forKey:[keys objectAtIndex:i]];
}
}
else {
return input;
}
return result;
}
I hope this tutorial helps, who expect answer for this question.
-(void)saveToUserDefaults:(NSString*)myServerName uname:(NSString*)myUserName
pass:(NSString*)myPassword
{
NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
if (standardUserDefaults) {
[standardUserDefaults setObject:myServerName forKey:#"ServerKey"];
[standardUserDefaults setObject:myUserName forKey:#"UserNameKey"];
[standardUserDefaults setObject:myPassword forKey:#"PasswordKey"];
[standardUserDefaults synchronize];
}
}
-(NSArray*)retrieveFromUserDefaults
{
NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
NSString *serverName = nil;
NSString *userName = nil;
NSString *password = nil;
if (standardUserDefaults)
serverName = [standardUserDefaults objectForKey:#"ServerKey"];
userName = [standardUserDefaults objectForKey:#"UserNameKey"];
password = [standardUserDefaults objectForKey:#"PasswordKey"];
NSArray* credentials = [NSArray arrayWithObjects:serverName,userName,password, nil];
return credentials;
}
To Pass values
[self saveToUserDefaults:serverVariable uname:usernameVariable pass:passVariable];
To get Values
NSArray *result=[self retrieveFromUserDefaults];
Happy coding!!!
The contents of your array can only by plist valid objects: (NSString, NSNumber, NSDate, NSData, NSArray, or NSDictionary objects).
See documentation for NSUserDefaults setObject:forKey: and What is a Property List?
Your code needs a lot of clean up. Here is the simple and correct way to access standard user defaults:
The value you pass to your save method does not need to be mutable, although it can be. But since you are not mutating it inside your method, there's no need for it to be mutable. It just has to be not nil, which you'll check before saving:
-(void)saveToUserDefaults:(NSArray*)myArray
{
if (myArray) {
NSUserDefaults *myDefaults = [NSUserDefaults standardUserDefaults];
myDefaults[#"myArray"] = myArray;
}
}
Standard user defaults only returns non-mutable objects, which you can convert to a mutable copy using the "mutableCopy" method:
-(NSMutableArray*)retrieveFromUserDefaults
{
NSUserDefaults *myDefaults = [NSUserDefaults standardUserDefaults];
NSMutableArray *val = [[NSMutableArray alloc] init];
val = [myDefaults[#"MyArray"] mutableCopy];
return val;
}

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

have to save UITextfield's value to the NSUserDefault

I am a new comer to the iPhone world, I am having a question,I am having a login page in which 2 levels and associated 2 uitextfield,i have to save both the UITextfield's Values(inputt by user) to the NSUserDefault,and new time when we start application both the UITextfield should be filled with the values we hav input before....i am in bid trouble
code would be appreciated
Thanx in advance
-(void)saveLoginToUserDefaults:(NSString*)loginString
{
NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
if (standardUserDefaults) {
[standardUserDefaults setObject:loginString forKey:#"Login"];
}
}
-(NSString*)retrieveLoginFromUserDefaults
{
NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
NSString *val = nil;
if (standardUserDefaults)
val = [standardUserDefaults objectForKey:#"Login"];
return val;
}

Freaky UISwitch/UILabel.hidden/UIImageView.hidden Problem!

Sorry for the constant questions, but in my app, you are able to toggle if 3 UILabels and 1 UIImageview's hidden property is YES or NO via UISwitchs on another page (The settings page). The weird part is, one of the UILabels is hidden, even when it is declared that it is not to be hidden. Here is my code on the settings page.
- (IBAction)changeswitch1 {
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
if (artworkswitch.on)
[prefs setInteger:1 forKey:#"AWKey"];
else
[prefs setInteger:0 forKey:#"AWKey"];
}
- (IBAction)changeswitch2 {
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
if (titleswitch.on)
[prefs setInteger:1 forKey:#"TKey"];
else
[prefs setInteger:0 forKey:#"TKey"];
}
- (IBAction)changeswitch3 {
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
if (artistswitch.on)
[prefs setInteger:1 forKey:#"AKey"];
else
[prefs setInteger:0 forKey:#"AKey"];
}
- (IBAction)changeswitch4 {
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
if (volumeswitch.on)
[prefs setInteger:1 forKey:#"VKey"];
else
[prefs setInteger:0 forKey:#"VKey"];
}
All of this is set as the 'value changed' action in IB for the 4 switches.
Here is the code for the main page
if ([prefs integerForKey:#"AWKey"] == 1)
currentArtwork.hidden = NO;
else if ([prefs integerForKey:#"AWKey"] == 0)
currentArtwork.hidden = YES;
if ([prefs integerForKey:#"TKey"] == 1)
currentSong.hidden = NO;
else if ([prefs integerForKey:#"TKey"] == 0)
currentSong.hidden = YES;
if ([prefs integerForKey:#"AKey"] == 1)
currentArtist.hidden = NO;
else if ([prefs integerForKey:#"AKey"] == 0)
currentArtist.hidden = YES;
if ([prefs integerForKey:#"VKey"] == 1)
volumeview.hidden = NO;
else if ([prefs integerForKey:#"VKey"] == 0)
volumeview.hidden = YES;
This is just a guess, since I don't know the res of the code. But maybe it is hidden because another UILabel is positioned infront of it?. You can try:
[self.view bringSubviewToFront:yourLabel];
-Oscar
My solution was to have the label/imageview's hidden property set to NO upon the first launch.