cocoa - 对 NSArray 进行排序

标签 cocoa sorting nsarray

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

有人可以告诉我该怎么做吗?我无法理解 sortUsingSelectorsortUsingDescriptor 方法是如何工作的...

谢谢

最佳答案

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

当您对某些内容进行排序时,您希望最终结果排列为

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

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

<小时/>

1。 -sortUsingSelector:

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

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

例如,要对字符串列表进行不区分大小写的排序,可以使用 [arr sortUsingSelector:@selector(caseInsensitiveCompare:)] .

<小时/>

2。 -sortUsingFunction:context:

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

x <= y      is equivalent to      funcptr(x, y, ctx) <= 0
<小时/>

3。 -sortUsingDescriptors:

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

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

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

假设有2个键,整数x升序 then 和字符串 y降序,那么你可以写

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。

关于cocoa - 对 NSArray 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2849911/

相关文章:

cocoa - 拖放文件夹查看 cocoa

objective-c - 没有类指针的 C 回调

javascript - 如何优化代码?

cocoa - 基于 NSDate 类型的属性对自定义对象的 NSArray 进行排序

ios - 如何根据其中包含的某些值过滤数组

ios - 如何解析json值的动态变化。带有 2 个嵌套字典的字典,然后是数组,然后再次挖掘

Objective-C:从后台 Cocoa 应用程序显示一个弹出窗口

objective-c - kAudioUnitType_MusicEffect 子类型研究

mysql - 显示按 "on the fly score calculation"排序的带分页的文章的最佳做法是什么

python - 无法在终端中使用 sort 命令对 txt 文件中的数据进行排序