NSDictionary's allKeys array messed up - not in the order they are in the dictionary?

烂漫一生 提交于 2019-12-05 11:26:04

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.

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.

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.

You can create an NSArray with the Dictionary keys in the order you want.

Try this:

NSArray *array = [dict allKeys];

NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"self" ascending:NO];
NSArray *descriptors = [NSArray arrayWithObject:descriptor];

NSArray *orderedKeys = [array sortedArrayUsingDescriptors:descriptors];
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!