我想字符转换为基于预定值的整数,例如:基于值数组将NSString转换为NSInteger的最佳方式是什么?
a = 0
b = 1
c = 2
d = 3
等等
现在,我有做一个的if/else如果,我只是想知道我应该做的更快/更好的方式,因为转换列表可能会相当长。
下面是我使用的是什么现在:
-(NSInteger)ConvertToInt:(NSString *)thestring {
NSInteger theint;
if([thestring isEqualToString:@"a"] == YES){
theint = 0;
} else if ([thestring isEqualToString:@"b"] == YES){
theint = 1;
} //etc...
return theint;
}
这工作得很好,但正如我所说,如果它更有意义我可以创建一个数组的所有键/值,然后仅仅通过运行返回整数?
请提供示例,因为我是Objective C/iOS的初学者。我来自Web语言。
谢谢!
编辑:谢谢大家的帮助。我用taskinoors回答,但我换成这是给这个错误信息的NSDictionary:
NSDictionary *dict;
dict = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:0], @"a",
[NSNumber numberWithInt:1], @"b",
[NSNumber numberWithInt:2], @"c", nil];
对不起,我不太确定该怎么做。你能告诉我如何使它成为一个函数,我可以传递字符串“a”并返回一个整数。感谢您的意见。 – tsdexter 2012-04-09 19:48:14
我需要使用字符串,因为我也会有值,例如“ab”传入,这将需要返回一个整数。 – tsdexter 2012-04-09 19:50:31
@tsdexter如果你不明白这个例子,你应该更好地学习Objective-C和C. – 2012-04-09 19:50:31