Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is NSDictionary alphabetical in memory, but not in enumeration?

I understand that the right way to sort an NSDictionary is to create an array from the keys, sort the array, and then enumerate through the array and operate on the NSDictionary from there. My question is, for an NSDictionary *dict, with keys and values of strings,

Why is this alphabetical:

NSLog(@"%@", dict);

But this is not:

for (NSString *w in dict)
{
    NSLog(@"%@", w);
}

Seems odd... am I doing something wrong?

Thanks in advance.

like image 566
iBuys Avatar asked Feb 26 '23 19:02

iBuys


2 Answers

That's not "in memory" -- %@ causes a message to be called on dict, and that sorted it. Enumerating is meant to give you the fastest, raw access to the contents. If you need it sorted, you have to sort it.

Take a look at this free sorted dictionary for Objective-C

http://code.google.com/p/cocoa-sorted-dictionary/

like image 86
Lou Franco Avatar answered May 09 '23 15:05

Lou Franco


Because the first one sorts the array in exactly the way you describe, to make it easier for the user/programmer to find stuff. However, you’ll get the iteration order if you use the lower-level CFCopyDescription(dict).

The source code for the CoreFoundation collections is available, albeit without the Objective-C interface. NSDictionary/CFDictionary and NSSet/CFSet are based on CFBasicHash, which unsurprisingly implements a hash table. CFCopyDescription() and fast iteration loop over elements in memory order (CFBasicHashApply() and CFBasicHashGetBucket() in CFBasicHash.m). The actual ordering is designed for quick lookup based on hashing. If you’re not familiar with hash tables, see Wikipedia.

like image 41
Jens Ayton Avatar answered May 09 '23 15:05

Jens Ayton