365Cocoa

A snippet of Objective-C code per day, 365 days long.
Written by Pieter Omvlee, developer and owner of Bohemian Coding.

Mar 8

Day 10: -sortedArrayUsingKey

From time to time we need to sort things and having written code to do so a few times I noticed that quite often I’m sorting arrays by a certain key whether the array contains NSDictionary’s or not. Instead of messing around with NSSortDescriptor all the time I wrote yet another category-method:

@interface NSArray (NSArray_365Cocoa)
- (NSArray *)sortedArrayUsingKey:(NSString *)key
{
  return [self sortedArrayUsingDescriptors:
    [NSArray arrayWithObject:
      [[[NSSortDescriptor alloc] initWithKey:key ascending:YES] autorelease]]];
}

- (NSArray *)sortedArrayUsingKeys:(NSArray *)keys
{
  NSMutableArray *descriptors = [NSMutableArray array];
  for (NSString *key in keys)
    [descriptors addObject:
      [[[NSSortDescriptor alloc] initWithKey:key ascending:YES] autorelease]];
  
  return [self sortedArrayUsingDescriptors:descriptors];
}
@end

I don’t think I have to go in much detail here about how they work, many of my categories are just shorthands for things Apple already provides (and they provide quite a lot). Just a quick note here on blocks again. This code is part of Fontcase which is still 10.5 and hence does not use blocks. Using the -map: function from day 2 we can make this a bit shorter:

return [self sortedArrayUsingDescriptors:[keys map:^(id key) {
  return [[[NSSortDescriptor alloc] initWithKey:key ascending:YES] autorelease];
}];

Don’t you just love blocks? I really hope they’ll find their way to iPhone OS in 4.0.