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?