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

柔情痞子 提交于 2019-12-10 16:17:24

问题


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.


回答1:


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/




回答2:


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.



来源:https://stackoverflow.com/questions/4228691/why-is-nsdictionary-alphabetical-in-memory-but-not-in-enumeration

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