Thursday, May 20, 2010

How to sort NSMutableArray alphabetically

NSMutableArray contains dynamic info objects, which are removed and added by user. Removal is easy, but addition should be done in alphabetical order.
NSInteger myCompare(id item1, id item2, void *context)
    return [(NSString *)((MyItem *)item1).title
      (NSString *)((MyItem *)item1).title];

- (void)addItem:(MyItem *)aItem
    [self.myList addObject:aItem];
    NSArray *temp = [NSArray arrayWithArray:self.myList];
    self.myList = [NSMutableArray arrayWithArray:
      [temp sortedArrayUsingFunction:myCompare context:NULL]];
Might be more fun to write your own Yet Another Search And Insert In Right Location algorithm, but this was fast to code, safe implementation and guaranteed to work.

What are your priorities: writing YASAIIRL algorithms or other features?

No comments:

Post a Comment