When I add values in NSMutableDictionary
it automatically set Key wise. How can i disable it and arrange as per first set first and second set second.
NSMutableDictionary* filteredDictionary = [NSMutableDictionary dictionary];
[filteredDictionary setObject:@"abc" forKey:@"1"];
[filteredDictionary setObject:@"abc" forKey:@"3"];
[filteredDictionary setObject:@"abc" forKey:@"2"];
[filteredDictionary setObject:@"abc" forKey:@"5"];
[filteredDictionary setObject:@"abc" forKey:@"4"];
NSLog(@"%@",filteredDictionary);
current output:
{
1 = abc;
2 = abc;
3 = abc;
4 = abc;
5 = abc;
}
but i want
{
1 = abc;
3 = abc;
2 = abc;
5 = abc;
4 = abc;
}
Is there any way to disable sorting as per key?
Here's a way of doing it:
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"key" ascending:YES comparator:^(id obj1, id obj2) {
if (obj1 > obj2) {
return (NSComparisonResult)NSOrderedDescending;
}
if (obj1 < obj2) {
return (NSComparisonResult)NSOrderedAscending;
}
return (NSComparisonResult)NSOrderedSame;
}];
NSArray *sortedKeys = [[filteredDictionary allKeys] sortedArrayUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];
NSMutableDictionary *orderedDictionary = [NSMutableDictionary dictionary];
for (NSString *index in sortedKeys) {
[orderedDictionary setObject:[filteredDictionary objectForKey:index] forKey:index];
}
filteredDictionary = orderedDictionary;
NSDictionary
isn't sorting your keys, the order of keys in a dictionary is not defined since it's an unordered collection.
That means that you can't trust the order of the elements when you fetch/print them unless you use keysSortedByValueUsingSelector:
or keysSortedByValueUsingComparator:
to sort them while fetching them.
You can also see this in the manual of allKeys;
Return Value
A new array containing the dictionary’s keys, or an empty array if the dictionary has no entries.Discussion
The order of the elements in the array is not defined.
There is no way to keep keys/values ordered as you want in an NSDictionary
, so if you need them ordered in the same order as they're added, you basically have two options;
NSArray
- at the same time as you add them to the NSDictionary
, and use that collection for the ordered access.keysSortedByValueUsingComparator:
to order it when fetching all keys from the array.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With