views:

40

answers:

1

Hi

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

Thanks a lot for your help!

Ps. The code should run on iOS 3.2

+2  A: 

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

quixoto
Don't ask me why, but I just realized how this system works when I read your post:) Awesome, now the stuff makes sense. Thanks a lot! I think the link posted as comment to my question is a shortcut to creating a separate custom method, yet your post certainly works too.
Robin