什么是基于值数组将NSString转换为NSInteger的最佳方法?

时间:2012-04-09 19:41:52

标签: objective-c ios type-conversion

我想根据预定值将字符转换为整数,例如:

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的初学者。我来自网络语言。

谢谢!

编辑:感谢大家的帮助。我使用了taskinoors的答案,但是我替换了NSDictionary,它提供了错误消息:

NSDictionary *dict;
dict = [NSDictionary dictionaryWithObjectsAndKeys:
        [NSNumber numberWithInt:0], @"a",
        [NSNumber numberWithInt:1], @"b",
        [NSNumber numberWithInt:2], @"c", nil];

2 个答案:

答案 0 :(得分:4)

unichar ch = [thestring characterAtIndex:0];
theint = ch - 'a';

请注意,带有单引号的'a'为字符a,而不是字符串"a"

如果值与您的示例不一样,那么您可以将所有预定义值存储到字典中。例如:

"a" = 5;
"b" = 1;
"c" = 102;

NSArray *values = [NSArray arrayWithObjects:[NSNumber numberWithInt:5],
    [NSNumber numberWithInt:1], [NSNumber numberWithInt:102], nil];
NSArray *keys = [NSArray arrayWithObjects:@"a", @"b", @"c", nil];
NSDictionary *dic = [NSDictionary dictionaryWithObjects:values forKeys:keys];

theint = [[dic valueForKey:thestring] intValue];

答案 1 :(得分:1)

如果你想在字符串映射到整数的过程中保持一定的灵活性,并且你的整数从0到n-1运行,你在数组中有n个唯一项,你可以这样做:

-(NSInteger)ConvertToInt:(NSString *)thestring {
    NSArray *arr = [NSArray arrayWithObjects:@"a", @"b", @"c", @"d", nil];
    NSInteger theint = [arr indexOfObject:thestring];
    return theint;
}

现在这将每次构建数组,效率非常低,最佳方法是在类中构建一次数组,然后使用indexOfObject方法调用对该数组的引用。

相关问题