gpt4 book ai didi

ios - 根据 NSDictionaries 的 NSArray 中的值为 UITableView 创建索引

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:08:06 24 4
gpt4 key购买 nike

我在从包含许多 NSDictionariesNSArray 创建索引时遇到问题,我想在其中仅基于 username 索引值字典中的关键字。例如,每个词典看起来像这样:

{
username => "daspianist", //<- Only want to use this value to create index
objectId => "hjd72h3jd",
createdAt => "30-1-2014",
updatedAt => "30-1-2014"
}

目前我已经简化了这个问题,所以我正在索引 NSStringsNSArray,我所做的是:

//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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com