Posted by: bearc0025 | February 6, 2010

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)…


+(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;
}



Advertisements

Responses

  1. hi, nice article, thanks fro sharing

  2. hi
    It’s nice article, thank you for sharing and make i solve my problem.
    I reference this article for my article same content in thai langauge at http://wp.me/p1g5Io-my and thank you very much.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: