Fast enumeration of an NSDictionary instance ordered by key

Overview

  • I use quick enumeration to iterate through an instance of NSDictionary.
  • I expected an instance of NSDictionary to list based on the increasing order of the key, but that doesn't seem to be the case.

What I want to do:

  • I want to be able to iterate through an instance of NSDictionary in ascending order of key using quick enumeration

Note: Pls see the expected output and actual output.

Questions

  • Am I mistaken in my implementation?
  • Does NSDictionary provide fast key-based guarantee enumeration?
  • If not, is there work to do this and still use a quick enumeration?

Example

#import<Foundation/Foundation.h> int main() { system("clear"); NSDictionary *d1 = nil; @autoreleasepool { d1 = [[NSDictionary alloc] initWithObjectsAndKeys: @"AAA", [NSNumber numberWithInt:10], @"BBB", [NSNumber numberWithInt:20], @"CCC", [NSNumber numberWithInt:30], nil]; } for(NSNumber* n1 in d1) //I expected fast enumeration for NSDictionary to be based on the //ascending order of the key but that doesn't seem to be the case { printf("key = %p" "\t [key intValue] = %i" "\t value = %s\n", n1, [n1 intValue], [[d1 objectForKey:n1] UTF8String]); } return(0); } 

Expected Result

 key = 0xa83 [key intValue] = 10 value = AAA key = 0x1483 [key intValue] = 20 value = BBB key = 0x1e83 [key intValue] = 30 value = CCC 

Actual output

 key = 0x1e83 [key intValue] = 30 value = CCC key = 0xa83 [key intValue] = 10 value = AAA key = 0x1483 [key intValue] = 20 value = BBB 
+4
source share
3 answers
  • There is no correct implementation.
  • NSDictionary fast enumeration does not guarantee sorting (and it does not output anything due to its implementation as a hash container).
  • No, you need to sort it yourself.
+2
source
 for (NSString *key in [[d1 allKeys] sortedArrayUsingSelector:@selector(compare:)]) { id value = [d1 valueForKey:key]; ... } 
+13
source

There are no guarantees regarding the order in which you receive your property.

Allkeys
Returns a new array containing dictionary keys.
- (NSArray *) allKeys
Return value
A new array containing dictionary keys, or an empty array if the dictionary has no entries.
Discussion
The order of the elements in the array is not defined .

So my suggestion is that if your dictionary does not change often, cache the NSArray using the key in the order you want.
If your vocabulary changes frequently, you may need to sort allKeys when you need them.

+1
source

Source: https://habr.com/ru/post/1386641/


All Articles