gpt4 book ai didi

iphone - 如何从 NSDictionary 中提取特定数据对于某些键具有相等的值到组合的 NSArray 中

转载 作者:行者123 更新时间:2023-11-28 22:31:43 25 4
gpt4 key购买 nike

现在我有一个这样的字典,这只是一个例子,我有 A 到 Z:

(
{
id = 13;
name = "Roll";
firstLetter = R;
},
{
id = 14;
name = "Scroll";
firstLetter = S;
},
{
id = 16;
name = "Rock";
firstLetter = R;
},
{
id = 17;
name = "Start";
firstLetter = S;
}
)

我想提取具有相同 firstLetter 的字典并将它们组合成一个 NSArray 对象。预期结果如下:

R数组:

(
{
id = 13;
name = "Roll";
firstLetter = R;
},
{
id = 16;
name = "Rock";
firstLetter = R;
}
)

和S数组:

(

{
id = 14;
name = "Scroll";
firstLetter = S;
},
{
id = 17;
name = "Start";
firstLetter = S;
}
)

该怎么做?

最佳答案

我相信更好的方法是 Saohooou 建议的方法

但是可以优化为

NSArray *array = @[@{@"id": @13,@"name":@"Roll",@"firstLetter":@"R"},
@{@"id": @14,@"name":@"Scroll",@"firstLetter":@"S"},
@{@"id": @15,@"name":@"Rock",@"firstLetter":@"R"},
@{@"id": @16,@"name":@"Start",@"firstLetter":@"S"}];

NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
[array enumerateObjectsUsingBlock:^(NSDictionary *dict, NSUInteger idx, BOOL *stop) {
NSString *key = dict[@"firstLetter"];
NSMutableArray *tempArray = dictionary[key];
if (!tempArray) {
tempArray = [NSMutableArray array];
}
[tempArray addObject:dict];
dictionary[key] = tempArray;
}];
NSLog(@"%@",dictionary);

关于iphone - 如何从 NSDictionary 中提取特定数据对于某些键具有相等的值到组合的 NSArray 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17226547/

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