ios – 对NSDictionary进行排序,降序.如何使用`compare:options:`选择器发送选项?

ios – 对NSDictionary进行排序,降序.如何使用`compare:options:`选择器发送选项?,第1张

概述我试图对NSDictionary进行排序. 从Apple docs我看到你可以使用keysSortedByValueUsingSelector: NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithInt:63], @"Mathematics", [NSNumber 我试图对NSDictionary进行排序.

从Apple docs我看到你可以使用keysSortedByValueUsingSelector:

NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:    [NSNumber numberWithInt:63],@"Mathematics",[NSNumber numberWithInt:72],@"English",[NSNumber numberWithInt:55],@"History",[NSNumber numberWithInt:49],@"Geography",nil];NSArray *sortedKeysArray = [dict keysSortedByValueUsingSelector:@selector(compare:)];

这使:

// sortedKeysArray contains: Geography,History,Mathematics,English

但我想要:

// sortedKeysArray contains: English,Geography

我已经读过你可以使用compare:options:和NsstringCompareOptions来改变比较以便在另一个方向上进行比较.

但是我不明白你如何发送compare:options:在选择器中有一个选项.

我想做这样的事情:

NSArray *sortedKeysArray = [dict keysSortedByValueUsingSelector:@selector(compare:options:NSOrderDescending)];

我应该如何切换比较的顺序?

有关:
https://discussions.apple.com/thread/3411089?start=0&tstart=0

解决方法 选项1:使用比较器调用-compare:反过来:(感谢Dan Shelly!)
NSArray *blockSortedKeys = [dict keysSortedByValueUsingComparator: ^(ID obj1,ID obj2) {     // Switching the order of the operands reverses the sort direction     return [objc2 compare:obj1];}];

只需反转降序和升序返回语句,你应该得到你想要的.

选项2:反转您拥有的阵列:

见How can I reverse a NSArray in Objective-C?

总结

以上是内存溢出为你收集整理的ios – 对NSDictionary进行排序,降序.如何使用`compare:options:`选择器发送选项?全部内容,希望文章能够帮你解决ios – 对NSDictionary进行排序,降序.如何使用`compare:options:`选择器发送选项?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1102547.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-28
下一篇 2022-05-28

发表评论

登录后才能评论

评论列表(0条)

保存