Skip to content

Sort an Array of Custom Objects

When you have an array of custom objects (e.g., managed objects) and you don’t have a standard compare method to use or the ability to write one (i.e., will get overwritten if you recreate the class), you can use this technique to sort the objects based on a key-value (e.g., “name” below)…

[code]

+(NSArray*)sortArray:(NSArray*)arrayIn withKey:(NSString*)key;
{
NSSortDescriptor *sortDescriptor = [[[NSSortDescriptor alloc]
initWithKey:key ascending:YES] autorelease];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
NSArray *sortedArray = [arrayIn sortedArrayUsingDescriptors:sortDescriptors];

return sortedArray;
}

[/code]

0 thoughts on “Sort an Array of Custom Objects”