What I want to do seems pretty simple, but I can\'t find any answers on the web. I have an NSMutableArray
of objects, and let\'s say they are \'Person\' objects
Starting in iOS 4 you can also use blocks for sorting.
For this particular example I'm assuming that the objects in your array have a 'position' method, which returns an NSInteger
.
NSArray *arrayToSort = where ever you get the array from... ;
NSComparisonResult (^sortBlock)(id, id) = ^(id obj1, id obj2)
{
if ([obj1 position] > [obj2 position])
{
return (NSComparisonResult)NSOrderedDescending;
}
if ([obj1 position] < [obj2 position])
{
return (NSComparisonResult)NSOrderedAscending;
}
return (NSComparisonResult)NSOrderedSame;
};
NSArray *sorted = [arrayToSort sortedArrayUsingComparator:sortBlock];
Note: the "sorted" array will be autoreleased.