把你的字符串到一個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