OStack程序员社区-中国程序员成长平台

标题: ios - objective-c 中的 UserDefaults 数据验证 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 04:51
标题: ios - objective-c 中的 UserDefaults 数据验证

我想通过使用 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];
}



Best Answer-推荐答案


为了避免样板,您可以将 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;

关于ios - objective-c 中的 UserDefaults 数据验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52949996/






欢迎光临 OStack程序员社区-中国程序员成长平台 (https://ostack.cn/) Powered by Discuz! X3.4