3
\$\begingroup\$

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

}
\$\endgroup\$
4
\$\begingroup\$

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...

| improve this answer | |
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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