对 NSDictionary 的 NSArray 进行排序 [英] Sorting an NSArray of NSDictionary

查看:31
本文介绍了对 NSDictionary 的 NSArray 进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须对字典数组进行排序,但我必须按字典中的对象进行排序.

I have to sort an array of dictionaries but I have to order by an object in the dictionaries.

推荐答案

使用 NSSortDescriptors 和 -sortedArrayUsingDescriptors:.对于键路径,传入字典键,然后是要排序的对象键.在以下示例中,您有一个字典数组,这些字典在personDictionaryKey"下有一个人,而人"有一个姓氏"键.

Use NSSortDescriptors with -sortedArrayUsingDescriptors:. For the key path, pass in the dictionary key, followed by the object's key(s) by which you want to sort. In the following example, you have an array of dictionaries and those dictionaries have a person under "personDictionaryKey", and the "person" has a "lastName" key.

NSSortDescriptor * descriptor = [[[NSSortDescriptor alloc] initWithKey:@"personInDictionary.lastName" 
        ascending:YES] autorelease]; // 1
NSArray * sortedArray = [unsortedArray sortedArrayUsingDescriptors:
        [NSArray arrayWithObject:descriptor]];

1 - 在 10.6 中有用于创建排序描述符的类方便方法,但正如 bbum 的回答所说,现在有启用块的排序方法,我敢打赌它们会快得多.另外,我注意到您的问题是针对 iOS 的,所以这可能无关紧要.:-)

1 - In 10.6 there are class convenience methods for creating sort descriptors but as bbum's answer says, there are now blocks-enabled sorting methods and I'm betting they're a lot faster. Also, I noticed your question is for iOS, so that's probably irrelevant. :-)

这篇关于对 NSDictionary 的 NSArray 进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆