数组排序与自定义类的实例 [英] Sorting an array with instances of a custom class
问题描述
我充满了包含两个字符串的属性,名字和姓氏的自定义类的实例的数组。两者都有一个getter方法,它等于财产本身的名称。也有用于检索一个名为getFullName的人的全名的方法。考虑下面的例子。
I have an array filled with instances of a custom class which contains two String properties, firstname and lastname. Both have a getter method which is equal to the name of the property itself. There is also a method for retrieving the Full name of a person called "getFullName". Consider the example below.
CustomClass *person = [[CustomClass alloc] ...];
person.firstname // Returns "Thomas"
person.lastname // Returns "Meier"
[person getFullName] // Returns "Thomas Meier"
现在,我想这个阵列由全名的降序排列。我一直在寻找一些数组排序方法,但不太能弄清楚如何去这件事。我想,我必须创建某种比较函数用于比较两个元素,但我怎么知道哪个值传递给这个方法,我应该在哪里把它(自定义类或类所在的排序发生在SDK ?)。也许有一种要对此另一个/更好的办法?诚然,我已经接近无经验数组排序。
Now I would like to sort this Array by Fullname in a descending Order. I have been looking at some array sorting methods but was not quite able to figure out how to go about this. I guess that I have to create some kind of comparison function which compares two elements, yet how do I tell the SDK which values to pass to this method and where should I place it (in the custom class or in the class where the sorting happens?). Maybe there is another/better way of going about this? Admittedly I have close to none experience with sorting arrays.
非常感谢您的帮助!
诗。在code应该在iOS 3.2中运行
Ps. The code should run on iOS 3.2
推荐答案
有几个方法可以做到这一点。一种是把一个比较法上的自定义类。说它 -compare:
或类似的东西。该方法应该采取相同的自定义类型作为其输入的另一目的。它应该返回 NSOrderedAscending
, NSOrderedDescending
或 NSOrderedSame
,视该比较的结果。 (这里面比较功能,你看你自己的全名与传入的对象的全名)。
There are a couple ways to do this. One is to put a comparison method on the custom class. Call it -compare:
or something like that. That method should take another object of the same custom type as its input. It should return NSOrderedAscending
, NSOrderedDescending
, or NSOrderedSame
, depending on the result of the comparison. (Inside this compare function is where you look at your own fullName versus the passed-in object's fullName.)
然后你可以使用的NSMutableArray
的<一个href=\"http://developer.apple.com/iphone/library/documentation/cocoa/reference/foundation/Classes/NSMutableArray_Class/Reference/Reference.html#//apple_ref/occ/instm/NSMutableArray/sortUsingSelector%3a\"><$c$c>-sortUsingSelector:$c$c>方法是这样的:
Then you can use NSMutableArray
's -sortUsingSelector:
method, like this:
[myArray sortUsingSelector:@selector(compare:)];
这适用于iOS的所有版本。有4.0 +可用块比较的方法。
This works on all versions of iOS. There are block comparison methods available in 4.0+.
这篇关于数组排序与自定义类的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!