开发者

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

开发者 https://www.devze.com 2023-01-20 12:27 出处:网络
Is there a better way in Objective-C to do: if ([elementName isEqual:@\"one\"]){ // do some stuff } else if ([elementName isEqual:@\"two\"]]{

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

精彩评论

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

关注公众号