Reputation: 888
in my project I'm pulling data from a .plist, more concretely from an NSDictionary. I init a dictionary with the contents of the .plist, which works well. When I then do
NSArray *array = [dict allKeys];
it fills the array with all the keys, but in a totally random order, different to the order they are in the .plist file. I would really need to preserve the order. The keys in the dictionary are arrays, if that could cause a problem. What am I not getting?
Thanks a lot in advance!
Upvotes: 5
Views: 5331
Reputation: 1540
Try this:
NSArray *array = [dict allKeys];
NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"self" ascending:NO];
NSArray *descriptors = [NSArray arrayWithObject:descriptor];
NSArray *orderedKeys = [array sortedArrayUsingDescriptors:descriptors];
Upvotes: -1
Reputation: 4736
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.
Upvotes: 6
Reputation: 2053
You can create an NSArray with the Dictionary keys in the order you want.
Upvotes: 2
Reputation: 21383
As Qwerty Bob said, NSDictionary doesn't order its contents. If you need to persist an order for the keys, one way to do that would be to separately store an array of the keys in your .plist file. Then, enumerate the array and use that to access the dictionary values in order.
Upvotes: 3
Reputation:
Much like there is no order between items in an NSSet, there's is no inherent order to the key-value pairs within an NSDictionary.
If you want keys under a specific order, you'd need to use something like - (NSArray *)keysSortedByValueUsingComparator:(NSComparator)cmptr
but that won't give the order in which the NSDictionary was serialized in the plist file.
Upvotes: 7