-2

I think the following code speaks for itself.

if (card==1) {
    cardImageString = @"myGrabbedImage1.png";
} else if (card==2) {
    cardImageString = @"myGrabbedImage2.png";
} else if (card==3) {
    cardImageString = @"myGrabbedImage3.png";
} else if (card==4) {
    cardImageString = @"myGrabbedImage4.png";
} else if (card==5) {
    cardImageString = @"myGrabbedImage5.png";
} else if (card==6) {
    cardImageString = @"myGrabbedImage6.png";
} else if (card==7) {
    cardImageString = @"myGrabbedImage7.png";
} else if (card==8) {
    cardImageString = @"myGrabbedImage8.png";
}

The actual if-else is 10 times bigger than this.

Card = int.

CardImageString = NSString.

'card' is only used in this statement and can be removed in your answer.

How can I simplify all this??? Thanks!!

Vince
  • 648
  • 1
  • 7
  • 17

2 Answers2

7
cardImageString = [NSString stringWithFormat:@"myGrabbedImage%@.png", @(card)];
rmaddy
  • 314,917
  • 42
  • 532
  • 579
Krys Jurgowski
  • 2,871
  • 17
  • 25
  • @vince: You want to check the card if it is between 1 and 8 just incase. – rckoenes Nov 17 '14 at 16:02
  • In what locale would an `NSNumber` integer have a different output? I think boxing it into an `NSNumber` and printing it out is the most flexible because whether you use `int`, `long`, `NSInteger` or anything else, it works without having to cast to avoid compiler warnings. – Krys Jurgowski Nov 17 '14 at 16:17
  • 1
    OK, after further testing, it turns out I'm wrong. `stringWithFormat` uses the system locale, not the current locale. So regardless of the user's locale, the code in your answer will work. I need to make a trivial edit to your answer so I can undo my vote. Sorry about the confusion. – rmaddy Nov 17 '14 at 16:42
  • I was actually trying to find a way to test this and kept thinking I was setting my locale incorrectly. Thanks for updating. – Krys Jurgowski Nov 17 '14 at 16:44
3
    cardImageString = [NSString stringWithFormat:@"myGrabbedImage%d.png",card];
Onik IV
  • 5,007
  • 2
  • 18
  • 23