Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

My conditional code here seems repetitive and long. Is there a better approach? I want to test for a string value in a NSDictionary object and then depending upon the value prefix a UILabel with $, £, ¥ currency symbols.

I've just shown 2 examples below. I have more currencies and the code is very long.

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];

}
share|improve this question

1 Answer 1

up vote 4 down vote accepted

I'd create an NSDictionary holding those prefixes and wrap that whole thing into its own method, like so:

-(NSString *) prefixForCurrency:(NSString *)currency{
    NSDictionary *currencyPrefixes = @{@"EUR": @"€", @"USD" : @"$", @"GBP" : @"£", @"NOK" : @"kr." };
    NSString *returnString = [currencyPrefixes objectForKey:currency];  

    return returnString;
}

Then, instead of your current mass of if-statements you'd have something like the following:

NSString *currency = [item objectForKey:@"currency"];
NSString *currencyPrefix = [self prefixForCurrency: currency];

NSString *price = [item objectForKey:@"price"];
NSString *priceString = [NSString stringWithFormat:@"%@ %@", currencyPrefix, price];

In case you were wondering: the main reason I wrap the prefixDictionary in its own method is in case you'd for instance prefer to fetch this list from a file later on. Then you can just alter the innards of that one method...

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.