Reputation: 4320
Instead of using else if like this
if([screen isEqualToString :@"A"]){
}
else if(screen isEqualToString:@"B"){
}
Will it work like this
switch ([string isEqualToString:screen]){
case ISA:
break;
case ISB:
break;
default:
break;
}
where ISA and ISB is defined like
#define ISA [screen isEqualToString:A] and **will it be efficient**
Upvotes: 0
Views: 6598
Reputation: 100662
The literal answer is, as per ATaylor and ACB, no. Switches require integers and at best you'd end up doing a pointer comparison, which isn't the same as isEqualToString:
.
Options for cutting down the syntactic heft and processing cost of cascading if
tests are dictionary based — you could in principle fill a dictionary with blocks keyed on strings but then for most practical purposes you'd need to create the dictionary rather too often so I tend to fill with selectors. E.g.
NSDictionary *stringsToSelectors =
@{
@"A" : [NSValue valueWithPointer:@selector(doTaskA)],
@"B" : [NSValue valueWithPointer:@selector(doTaskA)],
};
SEL selector = [[stringsToSelectors objectForKey:string] pointerValue];
[self performSelector:selector];
...
- (void)doTaskA
{
// etc, etc
}
If you wanted to be even more naturally dynamic than that you could even go with:
NSString *selectorName = [NSString stringWithFormat:@"doTask%@", string];
SEL selector = NSSelectorFromString(selectorName);
if([self respondsToSelector:selector]) [self performSelector:selector];
...
- (void)doTaskA /* etc, etc */
Upvotes: 1
Reputation: 2598
No, I most certainly don't think so. switch/case is all about numeric if/then/else cases.
However what you COULD do is the following:
Write a function and pass it a variable number of arguments (since objective-c implements C look up va_args for the syntax). Pass it the original string and the strings you want to compare to.
Inside that function, use a 'for' loop, which compares the strings one by one until it either reaches the end or finds a match according to your criteria.
Once either is met, return the index. And that index you can use in switch case. A little example:
switch([self compareStrings:@"FirstString" Options:"@FirstString", @"SecondString"]) {
case 0: //FirstString
break;
case 1: //SecondString
break;
default: //Not found
break;
}
That should work. Regarding your function: Be sure to either incorporate an Optioncount, or make the options 'nil' terminated, because otherwise the function won't know when the end is actually reached.
Upvotes: 2