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];
}

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

相关文章

我正在用TitaniumDeveloper编写一个应用程序,它允许我使用Ja...
我的问题是当我尝试从UIWebView中调用我的AngularJS应用程序...
我想获取在我的Mac上运行的所有前台应用程序的应用程序图标....
我是一名PHP开发人员,我使用MVC模式和面向对象的代码.我真的...
OSX中的SetTimer在Windows中是否有任何等效功能?我正在使用...
我不确定引擎盖下到底发生了什么,但这是我的设置,示例代码和...