gpt4 book ai didi

ios - 如何根据键 "id"升序对 NSDictionary 进行排序?

转载 作者:行者123 更新时间:2023-11-29 01:05:06 24 4
gpt4 key购买 nike

你好这是我从服务器得到的

{
1 = {

"display_name" = "One";
id = 1;
};
2 = {

"display_name" = "Two";
id = 2;
};
13 = {

"display_name" = "abc";
id = 13;
};
15 = {

"display_name" = "aaa";
id = 15;
};
4 = {

"display_name" = "ffd";
id = 4;
};
3 = {

"display_name" = "abdfdfc";
id = 3;
};
5 = {

"display_name" = "aasdfsdfa";
id = 5;
};
}

我需要根据“id”对其进行排序,这就是输出结果

期待输出

{
1 = {

"display_name" = "One";
id = 1;
};
2 = {

"display_name" = "Two";
id = 2;
};
3 = {

"display_name" = "abdfdfc";
id = 3;
};
4 = {

"display_name" = "ffd";
id = 4;
};
5 = {

"display_name" = "aasdfsdfa";
id = 5;
};
13 = {

"display_name" = "abc";
id = 13;
};
15 = {

"display_name" = "aaa";
id = 15;
};
}

这段代码我已经试过了,但它不起作用

 //vehiclesDictionary   real dictionary
NSMutableArray *sortedKeys=[[NSMutableArray alloc]init];
for(NSString *item in [vehiclesDictionary allKeys]){
[sortedKeys addObject:[NSNumber numberWithInt:[item intValue]]];
}


NSArray *sortedKeysArray = [sortedKeys sortedArrayUsingSelector: @selector(compare:)];
NSLog(@"%@",sortedKeysArray);

NSMutableDictionary *sortedValues = [[NSMutableDictionary alloc] init];
for (NSString *key in sortedKeysArray) {
[sortedValues setValue:[vehiclesDictionary valueForKey:[NSString stringWithFormat:@"%@",key]] forKey:key];
}

NSLog(@"%@",sortedValues);

请帮帮我

最佳答案

您不能对 NSDictionary 进行排序,它是一种未排序的集合类型。您需要将键存储在一个数组中并对其进行排序,然后使用它按顺序访问 NSDictionary。

根据您上面的代码,可以修改如下,例如

NSDictionary *dict = [NSDictionary dictionary];

NSArray *sortedKeys = [[dict allKeys] sortedArrayUsingSelector:@selector(compare:)];

for (NSString *key in sortedKeys) {
NSLog(@"%@", [d objectForKey:key]);

// Do something with the object here
}

在这里,您可以使用 NSDictionary 传递sortedKeys 数组,并使用sortedKeys 数组按顺序访问您的NSDictionary。

一种更简洁的获取数组的方法,但与上面的结果相同,将使用:

NSDictionary -keysSortedByValueUsingComparator 如图所示 here .

关于ios - 如何根据键 "id"升序对 NSDictionary 进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36503056/

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