把你的字符串到一个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
}
词典的查找O(1),而一个数组的搜索可能是O(log n)的。对于15个元素来说并不重要,但作为一般规则,字典或集合可能表现更好。有些事情要考虑,如果你做这个搜索/比较了很多。
编辑
正如我提到的,NSSet
也会做查找在O(1)时间:
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
}
更干净的代码,肯定,但我认为NSSet
情况下,需要更长的时间来创造。但是你只需要做一次,对吧?
而不是使用空值的字典,可能'NSSet'会更适合。 – Hugh 2010-07-29 01:02:38
另外,你应该使用'objectForKey:'而不是'valueForKey:'和'NSDictionary'。对于'NSSet',使用'containsObject:'。 – jtbandes 2010-07-29 01:11:33
你说得对,我从记忆中打字。 – 2010-07-29 01:12:49