views:

66

answers:

3

Hello,

I want to compare a string with multiple string.For ex

if([var isEqualToString:@"Box"]||[var isEqualToString:@"Ball"]|[varisEqualToString:@"Bat"])
{
some function
}else{
some fuction
}

In my case i have to compare with 15 string, so i have to check for 15 times.Is there any other better way to compare it.Is there any small simple code will implement my logic.Thanks

A: 

You could create an array using

NSArray *stringArray = [NSArray arrayWithObjects: @"Box", @"Ball", @"Bat", nil];
if([NSArray indexOfObject:var] != NSNotFound)
{
   ...
}
else
{
   ...
}

Not really better, but possibly more readable.

BojanG
+1  A: 

Put your strings into an NSDictionary:

NSNull *nullValue = [NSNull null];
NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:nullValue, nullValue, ..., nil forKeys:@"Box", @"Ball", ..., nil];
if ([dictionary objectForKey:var]) {
    // var matches one of the keys, run function 
}
else { 
    // var doesn't match any of the keys, do something else
}

Dictionary lookups are O(1), whereas an array search is probably O(log n). Not a big deal for 15 elements, but as a general rule a dictionary or set will likely perform better. Something to think about if you do this search/comparison a lot.

EDIT

As I mentioned, an NSSet will also do lookups in O(1) time:

NSSet *comparisonSet = [NSSet setWithObjects:@"Box", @"Ball", ..., nil];
if ([comparisonSet containsObject:var]) {
    // var matches set object, run function
} 
else {
    // var doesn't match any of the set objects, do something else
}

Cleaner code, definitely, but I think NSSet instances take much longer to create. But then you only have to do it once, right?

Alex Reynolds
Rather than using a dictionary with null values, perhaps a `NSSet` would be better suited.
Huw Giddens
Also, you should be using `objectForKey:` instead of `valueForKey:` with `NSDictionary`. For `NSSet`, use `containsObject:`.
jtbandes
You're right, I'm typing from memory.
Alex Reynolds
+4  A: 

You're better off adding the strings to an NSSet as follows:

NSSet *mySet = [NSSet setWithObjects:@"Box", @"Ball", @"Bat", nil];
if([mySet containsObject:string]) {
} else {
}

A lot of the other solutions use arrays or dictionaries for the same purpose. Sets are the correct data structure for this since they are created for the purpose of containing unordered objects and testing membership. I'm pretty sure containsObject: runs in constant time compared to the same method in NSArray which needs to do an element search.

Elfred
Here's an interesting comparison between NSArray, NSSet, and related types: http://cocoawithlove.com/2008/08/nsarray-or-nsset-nsdictionary-or.html
NullUserException