I want to convert characters into integers based on predetermined values, for example:
a = 0
b = 1
c = 2
d = 3
etc…
Right now I’m doing it with an If/Else If, I just want to know if there is a faster/better way I should be doing it because the list of conversions may get quite long.
Here’s what I’m using now:
-(NSInteger)ConvertToInt:(NSString *)thestring {
NSInteger theint;
if([thestring isEqualToString:@"a"] == YES){
theint = 0;
} else if ([thestring isEqualToString:@"b"] == YES){
theint = 1;
} //etc...
return theint;
}
This works fine, but as I said, if it makes more sense can I create an array with all the key/values then just run through that to return the integers?
Please provide examples as I’m a beginner with Objective C/iOS. I come from Web languages.
Thanks!
EDIT: Thanks for the help everyone. I used taskinoors answer but I replaced the NSDictionary which was giving error messages with this:
NSDictionary *dict;
dict = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:0], @"a",
[NSNumber numberWithInt:1], @"b",
[NSNumber numberWithInt:2], @"c", nil];
Note that,
'a'with a single quote is charactera, not string"a".If the values are not regular like your example then you can store all predefined values into a dictionary. For example: