按子键对字典排序

发布于 2024-11-17 02:36:29 字数 369 浏览 0 评论 0原文

我了解如何通过将 allKeys 获取到 NSMutableArray 中、对数组进行排序并将其用作字典中的索引来显示字典排序内容,但是......

如果我想按其子键之一对父键进行排序该怎么办钥匙?

例如,具有父键 @"8979"、@"6754"、@8776"、@"9076" 等的字典具有子键/值对,例如:

@"pos", 8 @“位置”,4 @“位置”,10 @“pos”,7

等等。

我知道如何将父键排序为:@“6754”,@“8776”,@“8979”,@“9076”,

但如何根据各自的@“pos”子键对父键进行排序,结果是: @“6754”,@“9076”,@“8979”,@“8776”

???

I understand how to display a dictionaries sorted content by means of obtaining allKeys into an NSMutableArray, sorting the array and using it as an index into the dictionary, but....

What if I want to sort the parent keys by one of their child keys?

for example, a dictionary with parent keys @"8979", @"6754", @8776", @"9076" and so on have child key / value pairs like:

@"pos", 8
@"pos", 4
@"pos", 10
@"pos", 7

and so on.

I know how to sort the parent keys to be: @"6754", @"8776", @"8979", @"9076"

but how to sort the parent keys based on their respective @"pos" child key resulting in:
@"6754", @"9076", @"8979", @"8776"

???

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

韵柒 2024-11-24 02:36:29

您可以将其简化为一行:

NSArray *sortedArray = [keySort keysSortedByValueUsingComparator: ^(id obj1, id obj2) {
    return [(NSString *)obj1 compare:(NSString *)obj2];
}];

You can simplify this to a single line:

NSArray *sortedArray = [keySort keysSortedByValueUsingComparator: ^(id obj1, id obj2) {
    return [(NSString *)obj1 compare:(NSString *)obj2];
}];
|煩躁 2024-11-24 02:36:29

keysSortedByValueUsingSelector: 将让您提供一个比较器,该比较器传递字典中的值并返回键的有序数组。

keysSortedByValueUsingSelector: will let you supply a comparator that is passed the values from your dictionary and returns an ordered array of the keys.

櫻之舞 2024-11-24 02:36:29

这似乎对我有用......

 NSArray *sortedArray = [keySort keysSortedByValueUsingComparator: ^(id obj1, id obj2) {

    NSString *p1 = [obj1 objectForKey:@"pos"];
    NSString *p2 = [obj2 objectForKey:@"pos"];

    if (p1 > p2 ) {
        return (NSComparisonResult)NSOrderedDescending;

    }

    if (p1 < p2) {
        return (NSComparisonResult)NSOrderedAscending;
    }
    return (NSComparisonResult)NSOrderedSame;
}];

This appears to do the trick for me ....

 NSArray *sortedArray = [keySort keysSortedByValueUsingComparator: ^(id obj1, id obj2) {

    NSString *p1 = [obj1 objectForKey:@"pos"];
    NSString *p2 = [obj2 objectForKey:@"pos"];

    if (p1 > p2 ) {
        return (NSComparisonResult)NSOrderedDescending;

    }

    if (p1 < p2) {
        return (NSComparisonResult)NSOrderedAscending;
    }
    return (NSComparisonResult)NSOrderedSame;
}];
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文