If you want to sort based on the name, alphabetically, then this would be the easiest method:
Create a method of MyObject
that you'll use to sort the objects. compare:
is a common method name for this sort of situation. It should take an argument of the same type as the class, and return an NSComparisonResult
. For example:
-(NSComparisonResult)compare:(MyObject*)obj;
Since we want to compare these objects based on a property in the same way that objects of the type of that property are already compared, we can just return the result of that comparison:
-(NSComparisonResult)compare:(MyObject*)obj {
return [self.name compare:obj.name];
}
Now that this method is in place, it's as simple as calling sortUsingSelector:
on the array in which they're contained:
[array sortUsingSelector:@selector(compare:)];
The advantage to this approach isn't readily seen for such a simple compare:
method, but you can put whatever logic you want in the compare:
method.
For example, if you had a Person
class which contained a date of birth, first name, and last name, you could make your compare:
method sort first by D.O.B., and if those were equivalent, sort by last name, and if you still got an equivalent result, then sort by first name, etc. This is not so easy to do using NSSortDescriptor
methods (as far as I know).