对NSArray进行排序 [英] Sorting a NSArray

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

问题描述

我有一个 NSArray 对象。
这些对象有一个名为distance的int属性。我想按距离对数组进行排序。

I have a NSArray of objects. Those objects have an int attribute called "distance". I would like to sort my array by distance.

有人可以告诉我怎么做吗?我不能理解 sortUsingSelector sortUsingDescriptor 方法是如何工作的。

Could someone please tell me how to do that ? I can't understand how the sortUsingSelector or sortUsingDescriptor methods are working...


推荐答案

我假设你使用的是NSMutableArray,因为NSArray是不可变的。

I assume you're using an NSMutableArray, because an NSArray is immutable.

x1 <= x2 <= x3 <= x4 <= ... <= xN

如何定义< = ?在ObjC中有3个解决方案。

How to define this <=? There are 3 solutions in ObjC.

[arr sortUsingSelector:@selector(foo:)] code>意味着其元素将被比较为*

[arr sortUsingSelector:@selector(foo:)] means that its elements will be compared as*

x <= y      is equivalent to      [x foo:y] <= 0

例如,要对大小写不敏感的字符串列表进行排序, [arr sortUsingSelector:@selector(caseInsensitiveCompare:)]

For example, to sort a list of strings case-insensitively, you use [arr sortUsingSelector:@selector(caseInsensitiveCompare:)].

这类似于 -sortUsingSelector:,但它使用函数指针作为输入。 [arr sortUsingFunction:funcptr context:ctx] 表示其元素将被比较为

This is similar to -sortUsingSelector:, but it uses a function pointer as input. [arr sortUsingFunction:funcptr context:ctx] means that its elements will be compared as

x <= y      is equivalent to      funcptr(x, y, ctx) <= 0






3。 -sortUsingDescriptors:



这是最复杂的一个。它需要一个描述属性的预期顺序的NSSortDescriptors列表。一个基本示例:


3. -sortUsingDescriptors:

This is the most complicated one. It takes a list of NSSortDescriptors which describe the expected order of the properties. One basic example:

NSSortDescriptor* desc = [[NSSortDescriptor alloc] initWithKey:@"distance" ascending:YES];
[arr sortUsingDescriptors:[NSArray arrayWithObject:desc]];
[desc release];

描述符告诉排序例程按键排序 distance 以升序。

the descriptor tells the sort routine to "sort by the key distance in ascending order".

假设有两个键,整数 x y 降序,那么您可以写

Suppose there are 2 keys, integers x ascending then and strings y descending, then you may write

NSSortDescriptor* dx = [[NSSortDescriptor alloc] initWithKey:@"x" ascending:YES];
NSSortDescriptor* dy = [[NSSortDescriptor alloc] initWithKey:@"y" ascending:NO selector:@selector(caseInsensitiveCompare:)];
[arr sortUsingDescriptors:[NSArray arrayWithObjects:x, y, nil]];
[dx release];
[dy release];

等。

注意:*实际上,您只应该返回-1,0或1。

Note: * Actually you should only return -1, 0 or 1.

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

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