微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

cocoa – 帮助在两个属性中对NSArray进行排序(使用NSSortDescriptor?)

我有点像NSSortDescriptor n00b.不过,我认为它是我需要做的正确工具:

我有一个由带有键的对象组成的NSArray,比如“名字”和“时间”.这是一个例子,而不是用语言表达它:

input:

name: time
B: 4
C: 8
B: 5
C: 4
A: 3
C: 2
A: 1
A: 7
B: 6


desired output:

name: time
A: 1 <---
A: 3
A: 7
C: 2 <---
C: 4
C: 8
B: 4 <---
B: 5
B: 6

因此,值按“时间”排序,并按“名称”分组. A首先是因为他的时间值最小,而A的所有值都是相继的.然后是C,他的所有价值都是第二小的时间价值.我已经指出了确定名称排序方式的值;在每个名称组中,按时间排序.

如何以最有效的方式从输入到输出NSArray? (cpu-和内存方面,不一定是代码方式.)我如何为此构造NSSortDescriptors,或使用任何其他方法?我不想自己动手,除非这是最有效的方式.

解决方法

sortedArrayUsingDescriptors: NSArray方法可满足您的大部分需求:

The first descriptor specifies the primary key path to be used in sorting the receiver’s contents. Any subsequent descriptors are used to further refine sorting of objects with duplicate values. See NSSortDescriptor for additional information.

还需要使用nspredicate进行一些过滤:

NSSortDescriptor *timeSD = [NSSortDescriptor sortDescriptorWithKey: @"time" ascending: YES];

NSMutableArray *sortedByTime = [UnsortedArray sortedArrayUsingDescriptors: timeSD];
NSMutableArray *sortedArray = [NSMutableArray arrayWithCapacity:[sortedByTime count]];

while([sortedByTime count]) 
{
        id groupLead = [sortedByTime objectAtIndex:0];  
        nspredicate *groupPredicate = [nspredicate predicateWithFormat:@"name = %@",[groupLead name]];

        NSArray *group = [sortedByTime filteredArrayUsingPredicate: groupPredicate];

        [sortedArray addobjectsFromArray:group];
        [sortedByTime removeObjectsInArray:group];
}

我不知道这是否是最有效的方法,但在您有理由相信它导致问题之前,无需担心性能影响.这是不成熟的优化.我不会对这种方法性能有任何担忧.你必须相信这个框架,否则你最终会重写它(从而破坏框架的重点),因为没有根据的偏执.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐