Search code examples
iosuitextfieldnsuserdefaultstextcolor

How to use NSUserDefault with several preferenses and textColor


I have a UISwitch, witch among other things, disables a UITextfield. When using NSUserDefaults, I manage the switch to remember its current state (on/off)

NSString *const MyPrefKey =@"MyPrefKey";


 [[NSUserDefaults standardUserDefaults]
     setBool:[sender isOn]
     forKey:MyPrefKey];

The switch state is recalled in viewDidLoad with

 BOOL switchState =[[NSUserDefaults standardUserDefaults]boolForKey:MyPrefKey];
 [mySwitch setOn:switchState];

This works perfect, the position of the UISwitch is remembered.

For enabling the textfield when the switch changed

I tried as suggested:

 [[NSUserDefaults standardUserDefaults]
     setObject:[NSNumber numberWithBool:[myTextField isEnabled]]
     forKey:MyPrefKey];

and recalled with

BOOL mtf  =[[NSUserDefaults standardUserDefaults]boolForKey:MyPrefKey];
[myTextField setEnabled:mtf];

Which also worked fine. However, only one of these work at the time. How do I make more defaults to be set at the same time? Do I have to make several PrefKeys? or can all of them be stored in the same prefKey?

Finally I tried to change the textcolor with NSUserDefaults

[[NSUserDefaults standardUserDefaults]
     setObject: [myTextField textColor]
     forKey: MyPrefKey];

that causes a crash when recalled with

UIColor*newColor= [[NSUserDefaults standardUserDefaults] objectForKey: EfloraSharePrefKey];
[myTextField setTextColor:newColor];

So how do I use NSUserDefault with textColor? I would appriciate any good solutions.


Solution

  • You can save property list objects only to NSUserDefaults. You have to somehow serialize your color. A possible solution:

    CGFloat r, g, b, a;
    [myTextField.textColor getRed:&r green:&g blue:&b alpha:&a];
    NSNumber *rn, *gn, *bn, *an;
    rn = [NSNumber numberWithFloat:r];
    gn = [NSNumber numberWithFloat:g];
    bn = [NSNumber numberWithFloat:b];
    an = [NSNumber numberWithFloat:a];
    NSDictionary *color = [NSDictionary dictionaryWithObjectsAndKeys:
        rn, @"red",
        gn, @"green",
        bn, @"blue",
        an, @"alpha",
        nil];
    [[NSUserDefaults standardUserDefaults] setObject:color forKey:@"TextColor"];
    

    And to retrieve it:

    NSDictionary *color = [[NSUserDefaults standardUserDefaults] objectForKey:@"TextColor"];
    NSNumber *rn, *gn, *bn, *an;
    rn = [color objectForKey:@"red"];
    ...
    UIColor *c = [UIColor colorWithRed:[rn floatValue]
        green:[gn floatValue]
        blue:[bn floatValue]
        alpha:[an floatValue]];
    textField.textColor = c;
    

    If you want to be really elegant, you can wrap this into a category and even make UIColor NSCoding-comformant (in order to be able to directly persist it to the user defaults plist).