应用程序在搜索(过滤)NSDictionary

时间:2015-11-27 11:01:15

标签: ios objective-c search

所以我有以下代码:

我的.h文件

    @interface TableViewController : UITableViewController <UISearchBarDelegate,UITableViewDataSource,UITableViewDelegate>
{
    IBOutlet UITableView *myTableView;
    IBOutlet UISearchBar *mysearchBar;
        NSMutableArray *filteredList;
     BOOL isFiltered;
}
@property NSDictionary *iconSet;

@end

和.m文件中出现问题的部分。

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

if(searchText.length == 0)
{
    //bool in .h file
    isFiltered = NO;
}else
{
    isFiltered = YES;
    filteredList = [[NSMutableArray alloc] init];

    //self.iconSet is an NSDictionary (coming from a segue) formed like -(NSDictionary *) symbols { return self.symbols = @{@"":@"Heart With Arrow",@"❤️":@"Heavy Black Heart"}
    for (NSDictionary *theDictionary in self.iconSet) {

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

            if (stringRange.location != NSNotFound) {
                [filteredList addObject:theDictionary];
                break;
            }
        }
    }
}
[myTableView reloadData];
}

xCode并没有因为任何错误或警告而咆哮,但当我在搜索栏中按下一个字母或图标时,应用程序崩溃了,它会显示以下消息:

  

***由于未捕获的异常终止应用程序&#39; NSInvalidArgumentException&#39;,原因:&#39; - [__ NSCFConstantString countByEnumeratingWithState:objects:count:]:无法识别的选择器发送到实例0x1000f94d0&#39;

我已尝试在stackoverflow上查找,但是找不到我想要的答案。我希望有人能帮助我找到我(可能是愚蠢的)错误。

1 个答案:

答案 0 :(得分:1)

由于self.iconSet是一个字典,用for..in迭代它会给你作为字符串的键。因此,不需要第二个循环:

for (NSString *key in self.iconSet) {
    NSString *value = [self.iconSet objectForKey:key];
    ...
}

或更好:

[self.iconSet enumerateKeysAndObjectsUsingBlock:^(NSString *key, NSString *value, BOOL *stop) {
     ...
}]