【问题标题】:Removing all values (strings) matching a search term from arrays located in a dictionary?从位于字典中的数组中删除与搜索词匹配的所有值(字符串)?
【发布时间】:2011-08-07 23:28:15
【问题描述】:

目前我正在编写一个带有 tableView 的应用程序,类似于 iPhone 联系人应用程序中的那个。

在搜索栏旁边,一切正常(部分、右侧显示标题的栏、已配置单元格...)。如果 tableView 的数据是从数组加载的,我很熟悉如何执行此操作(搜索),但我的情况是它是从位于 NSDictionary 中的数组加载的。

字典看起来像

Key = "A" >> Value = "array = apple, animal, alphabet, abc ..."
Key = "B" >> Value = "array = bat, ball, banana ..."

如何删除与搜索词匹配的所有字符串(从所有字典的数组中)?

提前非常感谢:)

【问题讨论】:

    标签: iphone ios uitableview nsdictionary uisearchbar


    【解决方案1】:

    你可以这样做

    NSMutableDictionary *newItems = [NSMutableDictionary dictionary];
    for (NSString *key in oldItems) {
        NSMutableArray *newArray = [NSMutableArray array];
        for (NSString *item in [oldItems objectForKey:key]) {
            if ([item rangeOfString:searchTerm].location != NSNotFound) {
                [newArray addObject:item];
            }
        }
        if ([newArray count]) {
            [newItems setObject:newArray forKey:key];
        }
    }
    [oldItems release];
    oldItems = [newItems retain];
    

    我不知道这是否是最好的方法,或者它是否足够快,但请告诉我这是否适合您。

    【讨论】:

    • 不,它没有 :( 我需要它来搜索 tableView。输入第一个字母并重新加载 tableview 后,我只看到不包含该字母的字符串。之后应用程序崩溃:(
    • 嗯,你的问题说(我引用)How can I remove all strings (from all of the dictionary's arrays) matching the search term? 我知道在搜索你的表格后应该包含 DO NOT 包含搜索词的词...我是什么失踪?你能告诉我它在哪里崩溃吗?
    • 我不知道,我没有收到错误日志......我真的很抱歉问错了。我的意思是我怎样才能只保留包含搜索词的字符串
    • 我已经修改了答案以满足您的需要(即保留仅包含搜索词的值)。如果您仍然遇到错误,请告诉我。
    【解决方案2】:

    您想用排除该字符串的新数组来更新现有字典吗?

    NSMutableDictionary* excludedDictionary = [NSMutableDictionary dictionaryWithDictionary:existingDictionary];
    
    for(id key in [existingDictionary allKeys])
    {
       NSArray* existingArray = [existingDictionary objectForKey:key];
       NSPredicate* predicate = [NSPredicate predicateWithFormat:@"self != %@", excludedString];
       NSArray* excludedArray = [existingArray filteredArrayUsingPredicate:predicate];
       [excludedDictionary setObject:excludedArray forKey:key];
    }
    existingDictionary = [NSDictionary dictionaryWithDictionary:excludedDictionary];
    

    这会将您现有的字典替换为其中没有字符串的字典...

    【讨论】:

      【解决方案3】:

      从各位 cmets 得知,您希望根据用户在文本字段中输入的内容来过滤表格内容。为此,您无需在每次更改字符时都修改字典。 UISearchDisplayController 正是针对这种情况提供的。详情请看参考:http://developer.apple.com/library/ios/#documentation/UIKit/Reference/UISearchDisplayController_Class/Reference/Reference.html

      HTH,

      阿克谢

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-08-08
        • 1970-01-01
        • 1970-01-01
        • 2011-09-30
        • 2019-05-27
        • 1970-01-01
        • 2015-03-11
        • 1970-01-01
        相关资源
        最近更新 更多