简体   繁体   English

对Objective-c对象数组进行排序

[英]Sorting an array of Objective-c objects

So I have a custom class Foo that has a number of members: 所以我有一个自定义类Foo ,它有许多成员:

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

And in another class I have an NSMutableArray containing a list of these objects. 在另一个类中,我有一个NSMutableArray其中包含这些对象的列表。 I would very much like to sort this array based on the dateCreated property; 我非常想根据dateCreated属性对这个数组进行排序; 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? 我知道我可以为此编写自己的分类器(迭代数组并根据日期重新排列)但我想知道是否有一个正确的Objective-C方法来实现这一目标?

Some sort of sorting mechanism where I can provide the member variable to sort by would be great. 我可以提供成员变量排序的某种排序机制会很棒。

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

Many thanks 非常感谢

That's quite simple to do. 这很简单。

First, in your Foo object, create a method 首先,在您的Foo对象中,创建一个方法

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

Which will return 哪个会回归

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

In the end, call on the array 最后,调用数组

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

Hope this helps, Paul 希望这有帮助,保罗

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM