NSDictionary with ordered keys NSDictionary with ordered keys objective-c objective-c

NSDictionary with ordered keys


The solution of having an associated NSMutableArray of keys isn't so bad. It avoids subclassing NSDictionary, and if you are careful with writing accessors, it shouldn't be too hard to keep synchronised.


I'm late to the game with an actual answer, but you might be interested to investigate CHOrderedDictionary. It's a subclass of NSMutableDictionary which encapsulates another structure for maintaining key ordering. (It's part of CHDataStructures.framework.) I find it to be more convenient than managing a dictionary and array separately.

Disclosure: This is open-source code which I wrote. Just hoping it may be useful to others facing this problem.


There is no such inbuilt method from which you can acquire this. But a simple logic work for you. You can simply add few numeric text in front of each key while you prepare the dictionary. Like

NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:                       @"01.Created",@"cre",                       @"02.Being Assigned",@"bea",                       @"03.Rejected",@"rej",                       @"04.Assigned",@"ass",                       @"05.Scheduled",@"sch",                       @"06.En Route",@"inr",                       @"07.On Job Site",@"ojs",                       @"08.In Progress",@"inp",                       @"09.On Hold",@"onh",                       @"10.Completed",@"com",                       @"11.Closed",@"clo",                       @"12.Cancelled", @"can",                       nil]; 

Now if you can use sortingArrayUsingSelector while getting all keys in the same order as you place.

NSArray *arr =  [[dict allKeys] sortedArrayUsingSelector:@selector(localizedStandardCompare:)];

At the place where you want to display keys in UIView, just chop off the front 3 character.