带有有序键的 NSDictionary [英] NSDictionary with ordered keys

查看:33
本文介绍了带有有序键的 NSDictionary的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 NSDictionary(存储在 plist 中),我基本上将它用作关联数组(字符串作为键和值).我想将键数组用作我的应用程序的一部分,但我希望它们按特定顺序排列(实际上并不是我可以编写算法将它们排序的顺序).我总是可以存储一个单独的键数组,但这似乎有点麻烦,因为我总是必须更新字典的键以及数组的值,并确保它们始终对应.目前我只使用 [myDictionary allKeys],但显然这会以任意的、非保证的顺序返回它们.Objective-C 中是否有我遗漏的数据结构?有人对如何更优雅地执行此操作有任何建议吗?

I have an NSDictionary (stored in a plist) that I'm basically using as an associative array (strings as keys and values). I want to use the array of keys as part of my application, but I'd like them to be in a specific order (not really an order that I can write an algorithm to sort them into). I could always store a separate array of the keys, but that seems kind of kludgey because I'd always have to update the keys of the dictionary as well as the values of the array, and make sure they always correspond. Currently I just use [myDictionary allKeys], but obviously this returns them in an arbitrary, non-guaranteed order. Is there a data structure in Objective-C that I'm missing? Does anyone have any suggestions on how to more elegantly do this?

推荐答案

具有关联的 NSMutableArray 键的解决方案还不错.它避免了 NSDictionary 的子类化,并且如果您小心编写访问器,保持同步应该不会太难.

The solution of having an associated NSMutableArray of keys isn't so bad. It avoids subclassing NSDictionary, and if you are careful with writing accessors, it shouldn't be too hard to keep synchronised.

这篇关于带有有序键的 NSDictionary的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆