iOS 上的sortedArrayWithSelector 和 NSDictionnary
我有一个 NSDictionnary 数组,我想按 int 值对它们进行排序(键名为“age”)。 例如:
Dic1:年龄=30,性别=男; Dic2:年龄=24,性别=男;
数组:Dic1、Dic2;
现在,通过比较方法,我希望拥有:
Array : Dic2, Dic1;
我尝试了很多东西但不起作用。我使用 NSSortDescriptor 但它只在 iOS 4.0 之后可用:(
你有解决方案吗? 谢谢 !
编辑:
我在 NSDictionary 类别上编写了一个比较方法:
- (NSComparisonResult)compareGood:(NSDictionary *)otherObject
{
return [[self objectForKey:@"age"] compare:[otherObject objectForKey:@"age"]];
}
但是我遇到了这个崩溃错误:由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“* -[NSCFNumber比较:]:nil参数”
I have an array of NSDictionnary and I would like to sort them by an int value (the key is named "age").
For exemple :
Dic1 : age = 30, sex = male;
Dic2 : age = 24, sex = male;
Array : Dic1, Dic2;
Now with a compare method I would lik to have :
Array : Dic2, Dic1;
I tried lots of things but doesn't work. I as using NSSortDescriptor but it's only available since iOS 4.0 :(
Have you got a solution ?
Thanks !
EDIT :
I wrote a compare method on NSDictionary category :
- (NSComparisonResult)compareGood:(NSDictionary *)otherObject
{
return [[self objectForKey:@"age"] compare:[otherObject objectForKey:@"age"]];
}
But I have this crash error : Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '* -[NSCFNumber compare:]: nil argument'
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
NSSortDescriptor 的文档说:
对于 NSMutableArray 方法
-sortUsingDescriptors:
也是如此。您应该能够执行此操作:或者,如果 myArray 不可变,请对第二行执行此操作:
The documentation for NSSortDescriptor says:
Likewise for the NSMutableArray method
-sortUsingDescriptors:
. You should be able to do this:or, if myArray isn't mutable, do this for the second line: