开发者

Faster/Easier way to compare an NSString to a bunch of strings

Is there a better way in Objective-C to do:

if ([elementName isEqual:@"one"]){
   // do some stuff
}
else if ([elementName isEqual:@"two"]]{
   // do more stuff
}
else if ([elementName isEqual:@"three"]]{
   // do more开发者_如何转开发 stuff
}

ideally, I would like something like:


//BAD CODE, NOT REAL!!!

  switchString(elementName){
     @"one":
        // do stuff
        break;
     @"two":
        // do more stuff
        break;
     @"three":
        // do more stuff
        break;
    }


A little bit more concise

NSArray* array = [NSArray arrayWithObjects:@"one",@"two",@"three",nil];

int index = [array indexOfObject:elementName];

switch (index) {
    case 0:
        break;
    ...
    default:
        // -1 would be not fount      
}

another, a little bit more complicated way would be to store the strings and NSInvocations in a dictionary and the pull the invocation out using your element name as a key. I would do that if the "do stuff" part is more that a couple of lines in scope


No you did that correctly except I would use:

[elementName isEqualToString:@"one"]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜