【发布时间】:2014-01-30 15:38:19
【问题描述】:
我无法从包含许多NSDictionaries 的NSArray 创建索引,我想仅根据字典中的username 键索引值。例如,每个字典看起来像这样:
{
username => "daspianist", //<- Only want to use this value to create index
objectId => "hjd72h3jd",
createdAt => "30-1-2014",
updatedAt => "30-1-2014"
}
目前我已经简化了这个问题,以便我将NSArray 的NSStrings 编入索引,我所做的事情如下:
//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);
【问题讨论】:
-
所以你想要的最终结果是一本字典。键是单个字符串,值是字典数组(用户名匹配单个字符键)?
-
@Wain 是的,这是正确的。例如,结果字典中的
key为“A”,值是NSDictionaries中的username以“A”开头。
标签: ios objective-c uitableview nsarray nsdictionary