Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Disable NSDictionary Sort automatically key wise

Tags:

iphone

ipad

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?

like image 514
Hiren gardhariya Avatar asked Oct 04 '12 12:10

Hiren gardhariya


2 Answers

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;
like image 34
Simon Germain Avatar answered Sep 21 '22 15:09

Simon Germain


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;

  • Add them to/remove them from an ordered collection - such as an NSArray - at the same time as you add them to the NSDictionary, and use that collection for the ordered access.
  • Add a field to the data you're adding to the dictionary that counts up for every add, then use that field with keysSortedByValueUsingComparator: to order it when fetching all keys from the array.
like image 163
Joachim Isaksson Avatar answered Sep 18 '22 15:09

Joachim Isaksson