如何使用自定义对象对NSMutableArray进行排序? [英] How do I sort an NSMutableArray with custom objects in it?

查看:107
本文介绍了如何使用自定义对象对NSMutableArray进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做的事情似乎很简单,但我在网上找不到任何答案。我有一个 NSMutableArray 的对象,让我们说它们是'Person'对象。我想通过Person.birthDate对 NSMutableArray 进行排序,这是 NSDate

What I want to do seems pretty simple, but I can't find any answers on the web. I have an NSMutableArray of objects, and let's say they are 'Person' objects. I want to sort the NSMutableArray by Person.birthDate which is an NSDate.

我认为它与此方法有关:

I think it has something to do with this method:

NSArray *sortedArray = [drinkDetails sortedArrayUsingSelector:@selector(???)];

在Java中我会使我的对象实现Comparable,或者使用带有内联自定义比较器的Collections.sort。 ..你在Objective-C上做这个吗?

In Java I would make my object implement Comparable, or use Collections.sort with an inline custom comparator...how on earth do you do this in Objective-C?

推荐答案

比较方法



要么为对象实现compare方法:

Compare method

Either you implement a compare-method for your object:

- (NSComparisonResult)compare:(Person *)otherObject {
    return [self.birthDate compare:otherObject.birthDate];
}

NSArray *sortedArray = [drinkDetails sortedArrayUsingSelector:@selector(compare:)];



NSSortDescriptor(更好)



或通常甚至更好:

NSSortDescriptor (better)

or usually even better:

NSSortDescriptor *sortDescriptor;
sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"birthDate"
                                           ascending:YES];
NSArray *sortedArray = [drinkDetails sortedArrayUsingDescriptors:@[sortDescriptor]];

您可以通过向阵列添加多个键轻松地按多个键排序。也可以使用自定义比较器方法。请查看文档

You can easily sort by multiple keys by adding more than one to the array. Using custom comparator-methods is possible as well. Have a look at the documentation.

自从Mac以来,还可以使用块进行排序OS X 10.6和iOS 4:

There's also the possibility of sorting with a block since Mac OS X 10.6 and iOS 4:

NSArray *sortedArray;
sortedArray = [drinkDetails sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
    NSDate *first = [(Person*)a birthDate];
    NSDate *second = [(Person*)b birthDate];
    return [first compare:second];
}];



表现



-compare:和基于块的方法通常会比使用 NSSortDescriptor 快得多,因为后者依赖于KVC。 NSSortDescriptor 方法的主要优点是它提供了一种使用数据而不是代码来定义排序顺序的方法,这使得它很容易实现,例如进行设置,以便用户可以通过单击标题行对 NSTableView 进行排序。

Performance

The -compare: and block-based methods will be quite a bit faster, in general, than using NSSortDescriptor as the latter relies on KVC. The primary advantage of the NSSortDescriptor method is that it provides a way to define your sort order using data, rather than code, which makes it easy to e.g. set things up so users can sort an NSTableView by clicking on the header row.

这篇关于如何使用自定义对象对NSMutableArray进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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