对Objective-c对象数组进行排序 [英] Sorting an array of Objective-c objects

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

问题描述

所以我有一个自定义类 Foo ,它有许多成员:

So I have a custom class Foo that has a number of members:

@interface Foo : NSObject {
    NSString *title;
    BOOL     taken;
    NSDate   *dateCreated;
}

在另一个班级我有一个 NSMutableArray 包含这些对象的列表。我非常希望根据 dateCreated 属性对此数组进行排序;我知道我可以为此编写自己的分类器(迭代数组并根据日期重新排列)但我想知道是否有一种正确的Objective-C方法来实现这一目标?

And in another class I have an NSMutableArray containing a list of these objects. I would very much like to sort this array based on the dateCreated property; I understand I could write my own sorter for this (iterate the array and rearrange based on the date) but I was wondering if there was a proper Objective-C way of achieving this?

我可以提供成员变量排序的某种排序机制会很棒。

Some sort of sorting mechanism where I can provide the member variable to sort by would be great.

在C ++中,我过去常常重载< =>运算符,这允许我按对象排序,但我有一种有趣的感觉Objective-C可能提供更好的选择?

In C++ I used to overload the < = > operators and this allowed me to sort by object, but I have a funny feeling Objective-C might offer a nicer alternative?

非常感谢

推荐答案

这很简单。

首先,在你的Foo对象中,创建一个方法

First, in your Foo object, create a method

- (NSComparisonResult) compareWithAnotherFoo:(Foo*) anotherFoo;

将返回

[[self dateCreated] compare:[anotherFoo dateCreated]];

最后,调用数组

[yourArray sortUsingSelector:@selector(compareWithAnotherFoo:)];

希望这会有所帮助,
Paul

Hope this helps, Paul

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

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