有一个更好的解决方案,弗朗索瓦。
从您的NSDictionary(我将在此处称为myDictionary)创建一个像这样的NSArray(在您的接口文件中声明):
NSArray *arrayForTableView;
然后,在您加载 NSDictionary 之后,执行以下操作:
arrayForTableView = [myDictionary allKeys]; // so you will have an array of all UserID's
现在,在您的 tableView: cellForRowAtIndexPath: 方法中,您可以这样做:
cell.textLabel.text = [myDictionary objectForKey:[arraForTableView objectAtIndex:indexPath.row]];
然后,当您想要在用户选择单元格时传递用户 ID 时,在您的 tableView: didSelectRowAtIndexPath: 中,您只需这样做:
id userIDSelected = [arraForTableView objectAtIndex:indexPath.row];
然后,当你想根据搜索过滤数组时,你可以简单地重新创建你的arrayForTableView,通过这种方式“扫描”你的 NSDictionary:
NSString *typedString;
NSMutableArray *arrayFiltered = [NSMutableArray array];
for (int i = 0; i < [[myDictionary allKeys] count]; i++)
{
if ([[myDictionary objectForKey:[[myDictionary allKeys] objectAtIndex:i]] rangeOfString:typedString].location != NSNotFound)
{
[arrayFiltered addObject:[[myDictionary allKeys] objectAtIndex:i]];
}
}
arrayForTableView = arrayFiltered;
这样,您甚至不需要更改 UITableView 数据源和委托方法。