我在从包含许多 NSDictionaries
的 NSArray
创建索引时遇到问题,我想仅根据用户名
对值进行索引字典中的键。如图所示,每个词典看起来都像这样:
{
username => "daspianist", //<- Only want to use this value to create index
objectId => "hjd72h3jd",
createdAt => "30-1-2014",
updatedAt => "30-1-2014"
}
目前,我已经简化了问题,以便为 NSStrings
的 NSArray
建立索引,我所做的如下:
//Note that `stringArray` is passed to this method
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
for (char firstChar = 'a'; firstChar <= 'z'; firstChar++)
{
NSString *firstCharacter = [NSString stringWithFormat:@"%c", firstChar];
NSArray *content = [stringArray filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"SELF beginswith[cd] %@", firstCharacter]];
NSMutableArray *mutableContent = [NSMutableArray arrayWithArray:content];
if ([mutableContent count] > 0)
{
NSString *key = [firstCharacter uppercaseString];
[dict setObject:mutableContent forKey:key];
NSLog(@"%@: %u", key, [mutableContent count]);
}
}
我正在努力将我为 NSStrings 所做的事情转换为 NSDictionaries 中 username
键的值,并且希望得到任何指导。谢谢!
更新
为了澄清,我感兴趣的结果字典看起来像这样
{
"a" => {
username => "aardvark",
otherKeys => "otherValues"
},
{
username => "applepicking",
otherKeys => "otherValues"
}
"d" => {
username => "daspianist",
otherKeys => "otherValues"
}
....
}
更新2
为了便于使用,根据 Wain
的答案键入的解决方案:
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
for (char firstChar = 'a'; firstChar <= 'z'; firstChar++)
{
NSString *firstCharacter = [NSString stringWithFormat:@"%c", firstChar];
NSArray *content = [userNamesArray filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"SELF beginswith[cd] %@", firstCharacter]];
NSMutableArray *mutableContent = [NSMutableArray arrayWithArray:content];
NSPredicate *p = [NSPredicate predicateWithFormat:@"username IN %@", content];
if ([mutableContent count] > 0)
{
NSString *key = [firstCharacter uppercaseString];
NSArray *values = [originalDictionary filteredArrayUsingPredicate:p];
[dict setObject:values forKey:key];
NSLog(@"%@: %lu", key, (unsigned long)[mutableContent count]);
}
}
NSLog(@"The dictionary is %@", dict);
最佳答案
因此,content
是与当前键匹配的username
数组。目标是找到该数组中包含 username
的所有字典。这是谓词的工作:
NSPredicate *p = [NSPredicate predicateWithFormat:@"username IN %@", content];
现在你可以做:
NSArray *values = [dictArray filteredArrayUsingPredicate:p];
[dict setObject:values forKey:key];
关于ios - 根据 NSDictionaries 的 NSArray 内的值创建 UITableView 的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21460812/