我有一个 NSMutableDictionary (PerosnsListSections) 和一个类名 Persons
NSMutableDictionary:
- 键是像“a,b,m ...”这样的字母
- 值为 NSMutableArray -> NSMutableArray 有类 Persons 的对象
人类: @property (assign,nonatomic) NSInteger pid; @property (strong,nonatomic) NSString *name;
现在我在 UITableView 中显示了 PerosnsListSections,如图所示
我想要实现的是,当用户首先在搜索栏中键入时,我必须过滤第一个字母的部分,然后过滤该部分下的名称。
对不起我的英语不好(:
最佳答案
您可以先通过以下操作在字典中选择正确的数组:
NSString *firstLetter = [searchString substringWithRange:(NSRange){0,1}];
NSArray *people = PersonsListSection[firstLetter];
然后您可以使用 NSPredicates
过滤人员:
NSPredicate *namesBeginningWithKeyword = [NSPredicate predicateWithFormat:@"(name BEGINSWITH[cd] $letter)"];
NSArray *filteredPeople = [people filteredArrayUsingPredicate:[namesBeginningWithKeyword predicateWithSubstitutionVariables:@{@"letter": searchString}]]);
不过,如何将其反射(reflect)在 tableview 的内容中是另一个问题。
- 通常,您希望 View Controller 成为 UISearchBar 的委托(delegate),并使用
– (void)searchBar:textDidChange:
委托(delegate)方法对更改使用react。 - 在那里你可以调用你的 tableview 的
- reloadData
方法,这样它会尝试重新计算它的内容,调用它的所有数据源方法,比如- numberOfSectionsInTableView:
等等。< - 反过来,在这些方法中,您需要检查是否在搜索栏中输入了一些文本,并使用上述提示返回正确的部分/单元格。
关于ios - 过滤/搜索 NSMutableDictionary,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22583229/