没有得到预期的NSComparison值

时间:2012-01-01 21:24:31

标签: objective-c string search string-comparison

我试图通过比较列表中的值('stringToCompare')和用户输入的搜索文本('searchText')来进行过滤。代码段如下。

NSComparisonResult result = [stringToCompare compare:searchText options:(NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch) range:NSMakeRange(0, [searchText length])];
NSLog(@"Search text: %@", searchText);
NSLog(@"string to compare: %@", stringToCompare);
NSLog(@"result: %i", result);
NSLog(@"NSOrderedsame: %i", NSOrderedSame);
if (result == NSOrderedSame)
{
   [self.filteredListContent addObject:genericObj];
}

但是,从下面的NSLog结果中可以看出,我似乎无法获得预期的结果。在这种情况下,我希望结果为'0',因为搜索文本'Xot'可以作为'stringToCompare'的一部分找到。我在这里缺少什么?

2012-01-02 05:13:59.184 onethingaday[5815:707] search text: Xot
2012-01-02 05:13:59.185 onethingaday[5815:707] string to compare: One exotic place you got laid in before. How was it?
2012-01-02 05:13:59.188 onethingaday[5815:707] result: -1
2012-01-02 05:13:59.188 onethingaday[5815:707] NSOrderedsame: 0

2 个答案:

答案 0 :(得分:2)

您正在比较整个字符串,而不是寻找出现的情况。试试这个:

NSRange r = [stringToCompare rangeOfString:searchText
                             options:NSCaseInsensitiveSearch];

if ( r.location != NSNotFound )
{
    NSLog(@"String found at position: %d",r.location);
}

答案 1 :(得分:1)

-compare:不搜索子字符串,它会比较范围内的完整字符串。你得到了预期的结果,向你展示字符串'Xot'如何与完整的字符串'你之前放置的一个异国情调的地方相比。怎么回事?'。