I’m just starting out in Objective-C, and have created an iOS program that I’d like to improve upon. In it, I’ve got two code blocks:
if ([stringTest isEqualToString:@"apple"]){
numTest=0;
}else if (([stringTest isEqualToString:@"orange"])||([stringTest isEqualToString:@"lemon"])){
numTest=1;
}else if ([stringTest isEqualToString:@"pumpkin"]){
numTest=2; // and so on...
And then the reverse:
if (numTest==0){
stringTest=@"apple";
} else if (numTest==1){
stringTest=@"orange/lemon";
} else if (numTest==2){
stringTest=@"pumpkin"; // and so on...
As these lists actually involve many more items, I’m sure there’s a much better way to do this. Any suggestions would be very much appreciated. Thanks for reading.
I would suggest setting up NSDictionaries that map the strings to numbers and numbers to strings. With the new object literal syntax:
The literal syntax for NSDictionary is
@{key: value, ...}. Note the use of @ symbols preceeding the numeric values; NSDictionary expects all keys and values to be objects.@1is equivalent to[NSNumber numberWithInt:1]. And The dictionary literal syntax is similar to[NSDictionary dictionaryWithObjectsAndKeys:@0, @"apple", ..., nil].Edit: generating the second dictionary from the first