Objective C: Sort array of objects

If we have array of some objects:
@interface SimpleObject : NSObject {
 NSInteger key;
 NSString *name;
        . . .
and we need to sort this array by "name" property of SimpleObject. Use NSSortDescriptor:
// declare array with SimpleObject instances
self.simpleObjectsArray = . . .

NSSortDescriptor *sortDescriptor =
        [[[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES] autorelease];
NSArray *sortDescriptors = 
        [NSArray arrayWithObject:sortDescriptor];
// array contained all instances sorted by "name" field
NSArray *sortedArray = 
        [self.simpleObjectsArray sortedArrayUsingDescriptors:sortDescriptors];

No comments:

Post a Comment