开发者

Sorting an array with instances of a custom class

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"

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 elemen开发者_如何转开发ts, 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.

Thanks a lot for your help!

Ps. The code should run on iOS 3.2


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.)

Then you can use NSMutableArray's -sortUsingSelector: method, like this:

[myArray sortUsingSelector:@selector(compare:)];

This works on all versions of iOS. There are block comparison methods available in 4.0+.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜