This question already has answers here:
How to store custom objects in NSUserDefaults
(7 answers)
Closed 8 years ago.
In my app I let users to pick a colour of background, tint and text. How can I save this settings after the app is closed? I mean when user again starts the app he wants to see the background, tint and text colour from previous usage.
This is how I have set the colours.
self.BackgroundView.backgroundColor = [UIColor colorWithRed:248.0/255.0 green:242.0/255.0 blue:229.0/255.0 alpha:1.0];
[[[self navigationController] navigationBar] setTintColor:[UIColor colorWithRed:103.0/255.0 green:10.0/255.0 blue:10.0/255.0 alpha:1.0]];
self.QuoteText.textColor = [UIColor colorWithRed:131.0/255.0 green:21.0/255.0 blue:21.0/255.0 alpha:1.0];
Trying to solve by following Greg's (probably the right) answer gives SIGABRT error by clicking on following button:
- (IBAction)setcolor:(id)sender {
UIColor *backgroundColor = [UIColor colorWithRed:230.0/255.0 green:230.0/255.0 blue:220.0/255.0 alpha:1.0];
self.BackgroundView.backgroundColor = backgroundColor;
UIColor *tintColor = [UIColor colorWithRed:129.0/255.0 green:165.0/255.0 blue:148.0/255.0 alpha:1.0];
[[[self navigationController] navigationBar] setTintColor:tintColor];
UIColor *textColor = [UIColor colorWithRed:0.0/255.0 green:98.0/255.0 blue:139.0/255.0 alpha:1.0];
self.QuoteText.textColor = textColor;
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:backgroundColor forKey:#"BACKGCOLOR"];
[defaults setObject:tintColor forKey:#"TINTCOLOR"];
[defaults setObject:textColor forKey:#"TEXTCOLOR"];
[defaults synchronize];
}
If user pick up colour instead of
self.BackgroundView.backgroundColor = [UIColor colorWithRed:248.0/255.0 green:242.0/255.0 blue:229.0/255.0 alpha:1.0];
You can do
UIColor *backgroundColor = [UIColor colorWithRed:248.0/255.0 green:242.0/255.0 blue:229.0/255.0 alpha:1.0];
self.BackgroundView.backgroundColor = backgroundColor;
NSData *backgroundColorData = [NSKeyedArchiver archivedDataWithRootObject:backgroundColor];
UIColor *tintColor = [UIColor colorWithRed:103.0/255.0 green:10.0/255.0 blue:10.0/255.0 alpha:1.0];
[[[self navigationController] navigationBar] setTintColor:tintColor];
NSData *tintColorData = [NSKeyedArchiver archivedDataWithRootObject: tintColor];
UIColor *textColor = [UIColor colorWithRed:131.0/255.0 green:21.0/255.0 blue:21.0/255.0 alpha:1.0];
self.QuoteText.textColor = textColor;
NSData *textColorData = [NSKeyedArchiver archivedDataWithRootObject: textColor];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject: backgroundColorData forKey:#"BACKGCOLOR"];
[defaults setObject:tintColorData forKey:#"TINTCOLOR"];
[defaults setObject:textColorData forKey:#"TEXTCOLOR"];
[defaults synchronize];
You do the same for tint and text colour (just use different key).
In the view controller where you want to change your view colour in viewDidLoad you do:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSData *backgColorData = [defaults objectForKey:#"BACKGCOLOR"];
UIColor *backgColor = [NSKeyedUnarchiver unarchiveObjectWithData:backgColorData];
NSData *tintColorData = [defaults objectForKey:#"TINTCOLOR"];
UIColor *tintColor = [NSKeyedUnarchiver unarchiveObjectWithData:tintColorData];
NSData *textColorData = [defaults objectForKey:#"TEXTCOLOR"];
UIColor *textColor = [NSKeyedUnarchiver unarchiveObjectWithData: textColorData];
if (backgColor)
self.BackgroundView.backgroundColor = backgColor;
if (tintColor)
[[[self navigationController] navigationBar] setTintColor:tintColor];
if (textColor)
self.QuoteText.textColor = textColor;
Apple is providing the NSUserDefaults for this, it does act like the preferences for your user / application. Example taken from here
Saving :
NSString *valueToSave = #"someValue";
[[NSUserDefaults standardUserDefaults]
setObject:valueToSave forKey:#"preferenceName"];
To get it back later :
NSString *savedValue = [[NSUserDefaults standardUserDefaults]
stringForKey:#"preferenceName"];
Test using nsuserdefaults to save the settings or, write to a plist.
Related
I've created a button that stops and plays background music when clicked. It works great, but when I click on the home button, and relaunch the application (background - foreground) the button doesn't work. I click on it and it does nothing. Help please!! Thanks
This is the code:
- (IBAction)muteButtonPressed:(id)sender {
UIImage *currentImage = [self.muteButton currentImage];
UIImage *vol1 = [UIImage imageNamed:#"Volume 1"];
UIImage *vol2 = [UIImage imageNamed:#"Volume 2"];
if ([currentImage isEqual:vol1]) {
[self.muteButton setImage:vol2 forState:UIControlStateNormal];
[self.backgroundMusic stop];
self.scene.playSounds = NO;
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setInteger:0 forKey:#"playSounds"];
[defaults synchronize];
}
if ([currentImage isEqual:vol2]) {
[self.muteButton setImage:vol1 forState:UIControlStateNormal];
[self playBackground];
self.scene.playSounds = YES;
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setInteger:1 forKey:#"playSounds"];
[defaults synchronize];
}
}
and this is the code in the viewcontroller :
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *playSoundsString = [defaults objectForKey:#"playSounds"];
NSInteger playSoundsInt = [playSoundsString intValue];
NSNumber *playSoundsNumber = [NSNumber numberWithInteger:playSoundsInt];
self.scene.playSounds = [playSoundsNumber boolValue];
if (self.scene.playSounds == YES) {
UIImage *vol1 = [UIImage imageNamed:#"Volume 1"];
self.scene.playSounds = YES;
[self playBackground];
[self.muteButton setImage:vol1 forState:UIControlStateNormal];
}
else if (self.scene.playSounds == NO) {
UIImage *vol2 = [UIImage imageNamed:#"Volume 2"];
self.scene.playSounds = NO;
[self.muteButton setImage:vol2 forState:UIControlStateNormal];
}
finally this is when my app enters background (in viewcontroller) :
if (self.scene.playSounds == YES) {
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(stopMusic:) name:#"SOUND_OFF" object:nil];
}
I got a UITextField as subview.
- (void)viewDidLoad {
[super viewDidLoad];
textField = [[UITextField alloc] initWithFrame:CGRectMake(21, 21, 159, 37)];
textField.borderStyle = UITextBorderStyleNone;
textField.font = [UIFont systemFontOfSize:15];
textField.placeholder = #"name";
textField.autocorrectionType = UITextAutocorrectionTypeNo;
textField.keyboardType = UIKeyboardTypeDefault;
textField.returnKeyType = UIReturnKeyDone;
textField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
textField.textColor = [UIColor whiteColor];
textField.keyboardAppearance = UIKeyboardAppearanceDark;
textField.delegate = (id) self;
textField.autocapitalizationType = UITextAutocapitalizationTypeNone;
[textField addTarget:self action:#selector(saveData:) forControlEvents:UIControlEventEditingDidEnd];
[self.view addSubview:textField];
}
-(void)saveData:(id)sender {
NSString *savestring = textField.text;
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:savestring forKey:#"savedstring"];
[defaults synchronize];
}
To load the data (viewDidLoad)
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *loadstring = [defaults objectForKey:#"savedstring"];
[textField setText:loadstring];
Now the problem is that it doesn't save and load the text of the UITextField.
First you need to enter some string in the Textfield and press return key, so that it will get a chance to call your "saveData" method and store the value in the NSUserDefaults. Just check all the values.
I found a solution:
textField.text = [defaults objectForKey:#"savedstring"];
Thanks everyone for your answers
"addSubview" after this method write to load the data method...
[self.view addSubview:textField];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *loadstring = [defaults objectForKey:#"savedstring"];
[textField setText:loadstring];
I'm trying to make a button's background change from background1 to background2 when it's clicked and stay on background2 even when the app is restarted.
I've managed to do that, but when I restart the app the background is malformed ( the background2 is a transparent circle) its showing the circle, but the transparent part becomes white..
The button is a custom one.
Any ideas?
Thanks guys
The problem were in the NSUserDefaults saving process, I now use this :
NSData *imageData = UIImagePNGRepresentation(contactImage);
Instead of :
NSData *imageData = UIImageJPEGRepresentation(contactImage, 100);
Hi this will be useful to you..
- (void)viewDidLoad
{
[super viewDidLoad];
NSData *colorData = [[NSUserDefaults standardUserDefaults] objectForKey:#"BackgroundColor"];
if (colorData != nil)
{
NSString *stringColor = [NSKeyedUnarchiver unarchiveObjectWithData:colorData];
CIColor *coreColor = [CIColor colorWithString:stringColor];
UIColor *color = [UIColor colorWithCIColor:coreColor];
[self.btnNext setBackgroundColor:color];
}
}
- (IBAction)next:(id)sender
{
[self.btnNext setBackgroundColor:[UIColor clearColor]];
CGColorRef colorRef = [UIColor clearColor].CGColor;
NSString *colorString = [CIColor colorWithCGColor:colorRef].stringRepresentation;
NSData *colorData = [NSKeyedArchiver archivedDataWithRootObject:colorString];
[[NSUserDefaults standardUserDefaults] setObject:colorData forKey:#"BackgroundColor"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
I have checked in ios 7 3.5 inch screen it is working..
but donot know on other deveices...
I have a set of NSString values like this:
self.dataArray = #[#"blue", #"orange", #"green", #"red", #"yellow"];
and would like to be able to do something like (after getting one of the above colors set to self.colorString):
self.view.backgroundColor=[UIColor self.colorString + Color];
but obviously can't do that. What is a possible way?
A nearly universal way:
NSDictionary *colors = #{
#"red": [UIColor redColor],
#"green": [UIColor greenColor],
#"blue": [UIColor blueColor]
};
NSString *name = #"blue";
UIColor *c = colors[name];
A truly universal way:
NSString *selName = [NSString stringWithFormat:#"%#Color", name];
SEL sel = NSSelectorFromString(selName);
UIColor *color = [[UIColor class] performSelector:sel];
You can try something like this:
SEL myColor = NSSelectorFromString([NSString stringWithFormat:#"%#Color", self.colorString]);
self.view.backgroundColor = [[UIColor class] performSelector:myColor]
Try to store associate your data with the colors in a dictionary:
UIColor *blue = [UIColor blueColor];
UIColor *red = [UIColor redColor];
NSDictionary *colors = #{#"blue" : blue, #"red" : red};
UITextField *pinga = [[UITextField alloc]init];
pinga.textColor = [colors objectForKey:#"red"];
I have a big problem and could not solve it for few days already.
When app loads at first time, I'm saving 4 colors to NSUserDeafaults in first UIViewController.
ViewController.m
AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
NSUserDefaults *sharedDefaults = [NSUserDefaults standardUserDefaults];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSInteger countValue = [defaults integerForKey:#"Array"];
if ([sharedDefaults boolForKey:#"FirstLaunch"])
{
[self openSubView];
[sharedDefaults setBool:NO forKey:#"FirstLaunch"];
[sharedDefaults synchronize];
[self saveColorsToDefaults];
// [prefs synchronize];
} // Do any additional setup after loading the view.
else if(countValue == 1)
{
}
}
-(void)saveColorsToDefaults{
const CGFloat *components1 = CGColorGetComponents([UIColor darkGrayColor].CGColor);
const CGFloat *components2 = CGColorGetComponents([UIColor blueColor].CGColor);
const CGFloat *components3 = CGColorGetComponents([UIColor redColor].CGColor);
const CGFloat *components4 = CGColorGetComponents([UIColor purpleColor].CGColor);
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setFloat:components1[0] forKey:#"cr"];
[prefs setFloat:components1[1] forKey:#"cg"];
[prefs setFloat:components1[2] forKey:#"cb"];
[prefs setFloat:components1[3] forKey:#"ca"];
[prefs setFloat:components2[0] forKey:#"cr2"];
[prefs setFloat:components2[1] forKey:#"cg2"];
[prefs setFloat:components2[2] forKey:#"cb2"];
[prefs setFloat:components2[3] forKey:#"ca2"];
[prefs setFloat:components3[0] forKey:#"cr3"];
[prefs setFloat:components3[1] forKey:#"cg3"];
[prefs setFloat:components3[2] forKey:#"cb3"];
[prefs setFloat:components3[3] forKey:#"ca3"];
[prefs setFloat:components4[0] forKey:#"cr4"];
[prefs setFloat:components4[1] forKey:#"cg4"];
[prefs setFloat:components4[2] forKey:#"cb4"];
[prefs setFloat:components4[3] forKey:#"ca4"];
[prefs synchronize];
NSLog(#"I just saved colors");
}
And after I need to set these colors to `DrawViewControllers drawing instruments.
I can get only last 3 colors but 1st color does not apears.
But when I set color for 1st instrument via colorPicker and save all the colors again to NSUserDefaults it works great!
-(void)LoadColorsAtStart
{
NSUserDefaults *prefers = [NSUserDefaults standardUserDefaults];
UIColor* tColor = [UIColor colorWithRed:[prefers floatForKey:#"cr"] green:[prefers floatForKey:#"cg"] blue:[prefers floatForKey:#"cb"] alpha:[prefers floatForKey:#"ca"]];
UIColor* tColor2 = [UIColor colorWithRed:[prefers floatForKey:#"cr2"] green:[prefers floatForKey:#"cg2"] blue:[prefers floatForKey:#"cb2"] alpha:[prefers floatForKey:#"ca2"]];
UIColor* tColor3 = [UIColor colorWithRed:[prefers floatForKey:#"cr3"] green:[prefers floatForKey:#"cg3"] blue:[prefers floatForKey:#"cb3"] alpha:[prefers floatForKey:#"ca3"]];
UIColor* tColor4 = [UIColor colorWithRed:[prefers floatForKey:#"cr4"] green:[prefers floatForKey:#"cg4"] blue:[prefers floatForKey:#"cb4"] alpha:[prefers floatForKey:#"ca4"]];
[prefers synchronize];
[self extractRGBforBlack:tColor];
[self extractRGBforBlue:tColor2];
[self extractRGBforRed:tColor3];
[self extractRGBforLine:tColor4];
[self.colorBar1 setTextColor:self.blackExtract];
[self.colorBar2 setTextColor:self.blueExtract];
[self.colorBar3 setTextColor:self.redExtract];
[self.colorBar4 setTextColor:self.lineExtract];
NSLog(#"I have extracted colors");
}
I have 5 similar DrawViewControllers and all works with Drawing UIView.
1.Store UIColor as nsdata into nsuserdefaults
NSData *colorData = [NSKeyedArchiver archivedDataWithRootObject:color];
2.Retrive UIColor from viewdidload
UIColor *color = [NSKeyedUnarchiver unarchiveObjectWithData:colorData];
Try this it will work without error
1.Store UIColor as NSString into NSUserDefaults
-(void)storeColor
{
NSString *colString = [NSString stringWithFormat:#"%#", [UIColor whiteColor]];
[[NSUserDefaults standardUserDefaults] setObject:colString forKey:#"keyFontColor"];
}
2.Convert string into UIColor while retrieve
-(void)retriveColor
NSArray *values = [[[NSUserDefaults standardUserDefaults] objectForKey:#"keyFontColor"] componentsSeparatedByString:#" "];
NSLog(#"%d",[values count]);
UIColor *def_color = [[UIColor alloc] init];
if ([values count]==5) {
CGFloat red = [[values objectAtIndex:1] floatValue];
CGFloat green = [[values objectAtIndex:2] floatValue];
CGFloat blue = [[values objectAtIndex:3] floatValue];
CGFloat alpha = [[values objectAtIndex:4] floatValue];
def_color = [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
self.dateLabel.textColor = def_color;
}
else if ([values count]==3)
{
CGFloat white = [[values objectAtIndex:1] floatValue];
CGFloat alpha = [[values objectAtIndex:2] floatValue];
def_color = [UIColor colorWithWhite:white alpha:alpha];
self.label.textColor = def_color;
}
else
{
// its store default value while app loads first time
self.label.textColor.textColor = [UIColor blackColor];
}
}