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

查看:175
本文介绍了如何使用自定义对象对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, 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和一个内联的自定义比较器。

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 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 *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
NSArray *sortedArray = [drinkDetails sortedArrayUsingDescriptors:sortDescriptors];

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

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天全站免登陆