我正在尝试创建一个 iOS 应用程序,其中涉及一个主要的 if 语句来检查文本框是否包含特定文本。我想检查某个单词的多个实例,但我不想执行多个 if 语句,因为这会大大降低应用程序的性能。
我如何检查一个单词是否与 NSArray 中的单词匹配,如果匹配,则在另一个文本框中返回与该单词关联的 NSString?
最佳答案
您可以创建一个NSDictionary
,将您正在检查的单词映射到您希望在输入该单词时返回的NSString
:
NSDictionary *words = [[NSDictionary alloc] initWithObjectsAndKeys:
@"word1", @"result1",
@"word2", @"result2",
/*etc*/
nil];
NSString *wordFromTextBox = ...;
NSString *result = [words objectForKey:keyword];
if (result != nil)
{
// use result
}
else
{
// word wasn't something we expected
}
// Some time later
[words release];
编辑:要遍历列表以便测试 关键字 是否包含在文本框中,您可以执行以下操作(假设 words
和 wordFromTextBox
和以前一样设置):
NSEnumerator *enumerator = [words keyEnumerator];
while ((NSString *keyword = [enumerator nextObject]) != nil)
{
if ([wordFromTextBox rangeOfString:keyword].location != NSNotFound)
{
NSLog(@"The text box contains keyword '%@'", keyword);
NSString *result = [words objectForKey:wordFromTextBox];
// Use the result somehow
break;
}
}
关于iphone - 更快的 if 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10194356/