-4

可能重复:
如果以更好的方式进行代码检查,我怎么能写这个?

我这里的条件代码似乎重复且冗长。有更好的方法吗?我想测试 NSDictionary 对象中的字符串值,然后根据 UILabel 的值前缀与 $、£、¥ 货币符号。

这是我的代码(我刚刚在下面展示了 2 个示例,我有更多货币并且代码很长):

  if ([[item objectForKey:@"currency"] isEqualToString:@"EUR"]) {

        NSString *priceConvertToStr = [NSString stringWithFormat:@"€%@", [[item objectForKey:@"price"]stringValue]];

        NSString *priceStringFix = [priceConvertToStr
                                    stringByReplacingOccurrencesOfString:@"(null)" withString:@""];

        priceLabelText.text = priceStringFix;
        [imgView2 addSubview:priceLabelText];

    }

    if ([[item objectForKey:@"currency"] isEqualToString:@"GBP"]) {
        NSString *priceConvertToStr = [NSString stringWithFormat:@"€%@", [[item objectForKey:@"price"]stringValue]];

        NSString *priceStringFix = [priceConvertToStr
                                    stringByReplacingOccurrencesOfString:@"(null)" withString:@""];

        priceLabelText.text = priceStringFix;
        [imgView2 addSubview:priceLabelText];

    }
    if ([[item objectForKey:@"currency"] isEqualToString:@"USD"]) {
        NSString *priceConvertToStr = [NSString stringWithFormat:@"$%@", [[item objectForKey:@"price"]stringValue]];

        NSString *priceStringFix = [priceConvertToStr
                                    stringByReplacingOccurrencesOfString:@"(null)" withString:@""];

        priceLabelText.text = priceStringFix;
        [imgView2 addSubview:priceLabelText];

    }

非常感谢您的帮助。

4

1 回答 1

3

您可以将您的代码重构为此(可能是因为if语句中基本上 80% 的代码是相同的):

NSDictionary *currDict = @{
    @"EUR": @"€",
    @"GBP": @"₤",
    @"USD": @"$"
};
NSString *currName = [item objectForKey:@"currency"];
NSString *currency = [currDict objectForKey:currName];

NSString *priceConvertToStr = [NSString stringWithFormat:@"%@%@",
    currency,
    [[item objectForKey:@"price"] stringValue]
];
NSString *priceStringFix = [priceConvertToStr stringByReplacingOccurrencesOfString:@"(null)" withString:@""];
priceLabelText.text = priceStringFix;
[imgView2 addSubview:priceLabelText];
于 2013-02-03T11:34:49.033 回答