为什么 NSDictionary 在内存中是按字母顺序排列的,但在枚举中却不是?
我知道对 NSDictionary 进行排序的正确方法是从键创建一个数组,对数组进行排序,然后枚举该数组并从那里对 NSDictionary 进行操作。我的问题是,对于 NSDictionary *dict,带有字符串的键和值,
为什么这是按字母顺序排列的:
NSLog(@"%@", dict);
但这不是:
for (NSString *w in dict)
{
NSLog(@"%@", w);
}
看起来很奇怪......我做错了什么吗?
提前致谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这不是“在内存中”—— %@ 导致在 dict 上调用一条消息,并对它进行排序。枚举旨在让您能够以最快的速度、原始方式访问内容。如果需要排序,就必须排序。
看看这个免费的 Objective-C 排序字典
http://code.google。 com/p/cocoa-sorted-dictionary/
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/
因为第一个完全按照您描述的方式对数组进行排序,以便用户/程序员更容易找到东西。但是,如果您使用较低级别的
CFCopyDescription(dict)
,您将获得迭代顺序。CoreFoundation 集合的源代码可用,尽管没有目标-C接口。
NSDictionary
/CFDictionary
和NSSet
/CFSet
基于CFBasicHash
,毫不奇怪,它实现了一个哈希表。CFCopyDescription()
和按内存顺序对元素进行快速迭代循环(CFBasicHash.m 中的CFBasicHashApply()
和CFBasicHashGetBucket()
)。实际排序是为了基于散列的快速查找而设计的。如果您不熟悉哈希表,请参阅维基百科。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
andNSSet
/CFSet
are based onCFBasicHash
, which unsurprisingly implements a hash table.CFCopyDescription()
and fast iteration loop over elements in memory order (CFBasicHashApply()
andCFBasicHashGetBucket()
in CFBasicHash.m). The actual ordering is designed for quick lookup based on hashing. If you’re not familiar with hash tables, see Wikipedia.