Array sorting has a built-in cistern that you must use because of the fast enumeration. For dictionary keys, I use a bubble view similar to this:
- (NSMutableArray*) bubbleSortDictKeys:(NSDictionary*)dict { if(!dict) return nil; NSMutableArray *sortedKeys = [NSMutableArray arrayWithArray: [dict allKeys]]; if([sortedKeys count] <= 0) return nil; else if([sortedKeys count] == 1) return sortedKeys; int n = [sortedKeys count] -1, i; BOOL swapped = YES; NSString *key1,*key2; NSComparisonResult result; while(swapped) { swapped = NO; for( i = 0; i < n; i++ ) { key1 = [sortedKeys objectAtIndex: i]; key2 = [sortedKeys objectAtIndex: i + 1]; result = [key1 compare: key2 options: NSCaseInsensitiveSearch]; if(result == NSOrderedDescending) { [key1 retain]; [key2 retain]; [sortedKeys exchangeObjectAtIndex:i withObjectAtIndex:i+1]; [key1 release]; [key2 release]; swapped = YES; } } } return sortedKeys; }
Then you can use this function as follows:
NSEnumerator *keys = [[self bubbleSortDictKeys:dict] objectEnumerator];
For reference, a list of built-in methods for sorting arrays is provided:
- sortedArrayHint
- sortedArrayUsingFunction: context:
- sortedArrayUsingFunction: context: tooltip:
- sortedArrayUsingDescriptors:
- sortedArrayUsingSelector:
- sortedArrayUsingComparator:
- sortedArrayWithOptions: usingComparator:
For completeness, in response to my comment below, you will learn how to use the sort descriptor for a key dictionary or any array:
NSArray *arrayToSort, *sortedArray; arrayToSort = [NSArray arrayWithObjects:car1, car2, car3, nil]; NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"color" ascending:YES]; sortedArray = [arrayToSort sortedArrayUsingDescriptors:[NSArray arrayWithObject:descriptor]];
Enjoy.
source share