使用NSDictionary时,UISearchBar会给出双重结果

时间:2017-06-15 20:46:13

标签: ios objective-c xcode cocoa-touch searchbar

它看起来像什么: http://imgur.com/a/jpvBi

我的textDidChange代码:

-(void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {

    if ([searchText length] == 0) {
        [_results removeAllObjects];
        [_results addObjectsFromArray:_testphrases];
        isFiltered = 0;
    } else {
        isFiltered = 1;
        [_results removeAllObjects];
        for (NSDictionary *string in _testphrases) {
            for (NSString *key in string) {
                NSString *value = [string objectForKey:key];
            NSRange r = [value rangeOfString:searchText options: NSCaseInsensitiveSearch];

            if (r.location != NSNotFound) {
                [_results addObject:string];
            }}
        }

    }
    [tableView reloadData];
    NSLog(@"%lu", (unsigned long)_results.count);
    NSLog(@"%lu", (unsigned long)_testphrases.count);

}

我使用NSDictionary并循环使用NSString。当我将NSCaseInsensitiveSearch更改为NSLiteralSearch时,此问题就会消失,但我需要将我的NSRange设为NSCaseInsensitiveSearch。谁能解释为什么它会给出重复的结果?

1 个答案:

答案 0 :(得分:0)

我想,你内心的循环问题。如果字典有更多两个键值对。

    NSDictionary *string = @{"name":"Good Morning", "message":"Good testing"};


    for (NSString *key in string) {
        NSString *value = [string objectForKey:key];
        NSRange r = [value rangeOfString:searchText options: NSCaseInsensitiveSearch];

        if (r.location != NSNotFound) {
            [results addObject:string];
        }
    }

注意:以上循环将运行两次。因此,您可以在数组中添加两次相同的值。