Sort an array with instances of a custom class

I have an array populated with instances of a custom class that contains two String properties, first and last name. Both have a getter method that 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 name in descending order. I looked at some methods for sorting arrays, but couldn't figure out how to do this. I suppose that I need to create some kind of comparison function that compares two elements, but how can I tell the SDK which values ​​to pass to this method and where to place it (in a custom class or in a class where sorting takes place?). Maybe there is another way? Admittedly, I have almost no experience in sorting arrays.

Many thanks for your help!

Ps. The code should work on iOS 3.2

+4
source share
1 answer

There are several ways to do this. One of them is to apply the comparison method to a custom class. Call it -compare: or something like that. This method must accept another object of the same user type as its input. It should return NSOrderedAscending , NSOrderedDescending or NSOrderedSame , depending on the result of the comparison. (Inside this comparison function, you see your own full name and the passed fullName object.)

Then you can use the NSMutableArray -sortUsingSelector: method, for example:

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

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

+5
source

All Articles