目标C中的UserDefaults数据验证

时间:2018-10-23 13:12:09

标签: ios objective-c string validation

我想通过使用if条件来验证我的NSUserDefaults字符串值。我已经完成了以下代码,但我正在寻找更好的验证方法。

NSString *savedValue = [[NSUserDefaults standardUserDefaults]
                            stringForKey:@"colordatafromthisvc"];

NSLog(@"%@colorValue---", savedValue);

if ([savedValue isEqualToString:@"black"]) {
    _imglet.image = [_imglet.image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
    [_imglet setTintColor:[UIColor blackColor]];

    _btnlet.tintColor = [UIColor blackColor];
} else if ([savedValue isEqualToString:@"pink"]) {
    _imglet.image = [_imglet.image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
    [_imglet setTintColor:[UIColor purpleColor]];

    _btnlet.tintColor = [UIColor purpleColor];
} else if ([savedValue isEqualToString:@"blue"]) {
    _imglet.image = [_imglet.image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
    [_imglet setTintColor:[UIColor blueColor]];

    _btnlet.tintColor = [UIColor blueColor];
} else if ([savedValue isEqualToString:@"red"]) {
    _imglet.image = [_imglet.image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
    [_imglet setTintColor:[UIColor redColor]];

    _btnlet.tintColor = [UIColor redColor];
} else if ([savedValue isEqualToString:@"yellow"]) {
    _imglet.image = [_imglet.image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
    [_imglet setTintColor:[UIColor yellowColor]];

    _btnlet.tintColor = [UIColor yellowColor];
} else {
    _imglet.image = [_imglet.image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
    [_imglet setTintColor:[UIColor orangeColor]];

    _btnlet.tintColor = [UIColor orangeColor];
}

1 个答案:

答案 0 :(得分:2)

为了避免样板,您可以将NSDictionary与所有有效选项一起使用。

NSDictionary *colors = @{@"black", [UIColor blackColor], @"pink": [UIColor purpleColor], @"blue": [UIColor blueColor], @"red": [UIColor redColor], @"yellow": [UIColor yellowColor]};

有了这本词典,您的代码应如下所示:

NSString *savedValue = [[NSUserDefaults standardUserDefaults]
                            stringForKey:@"colordatafromthisvc"];
UIColor *color = colors[savedValue] ?: [UIColor orangeColor];
_imglet.image = [_imglet.image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
[_imglet setTintColor:color];
_btnlet.tintColor = color;