我应该如何构造一个具有多个键的 NSDictionary?
我有一种情况,我想将一对对象映射到信息字典。我想避免创建 NSDictionaries of NSDictionaries of NSDictionaries 的 NSDictionary,因为这很令人困惑且难以维护。
例如,如果我有两个类,Foo 和 Bar,我想要 {Foo, Bar} -> {NSDictionary}
除了根据相关的两种类型创建自定义类(仅用作字典键)之外,还有其他选择吗?也许是类似于 STL 的配对类型但我不知道的东西?
I have a situation where I want to map a pair of objects to a dictionary of information. I'd like to avoid creating an NSDictionary of NSDictionaries of NSDictionaries since that's simply confusing and difficult to maintain.
For instance if I have two classes, Foo and Bar, I want {Foo, Bar} -> {NSDictionary}
Are there other options than just making a custom class (just to be used as the dictionary key) based on the two types in question? Maybe something akin to STL's pair type that I just don't know about?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
就像你说的,你可以创建一个 Pair 类:
编辑:
关于创建可以作为键的对象的一些注意事项:
NSCopying
协议,因为我们不希望键改变从我们下面。isEqual:
。我实现了hash
方法以达到良好的效果,但这可能不是必需的。Like you said, you can create a Pair class:
Edit:
Some notes on creating objects that can be keys:
NSCopying
protocol, since we don't want the key to change out from underneath us.isEqual:
. I implement thehash
method for good measure, but it's probably not necessary.您可以尝试 NSMapTable,然后您的密钥几乎可以是任何东西,如果您愿意的话,也许可以是指向结构的指针。
(以下评论的附录:NSMapTable 曾经不在 iOS 上,但从 iOS 6 开始可用。)
You could try NSMapTable, then your key can be pretty much anything, perhaps a pointer to a structure if you want.
(Addendum to the comments below: NSMapTable was once not on iOS, but is available as of iOS 6.)
效果的东西
使用[NSString stringWithFormat:@"%@ %@", [obj1 key_as_string], [oj2 key_as_string]]
对你没有好处,其中 key_as_string 是你的对象类的一部分?即从字符串中创建一个密钥。
Is using something to the effect of
[NSString stringWithFormat:@"%@ %@", [obj1 key_as_string], [oj2 key_as_string]]
no good for you, where key_as_string is part of your object class? i.e. make a key from a string.