Cocoa:使用枚举键的字典? [英] Cocoa: Dictionary with enum keys?

查看:122
本文介绍了Cocoa:使用枚举键的字典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要创建一个字典/ hashmap,其中

I need to create a dictionary/hashmap where the


  • 键是枚举

  • NSObject

  • Keys are enums
  • Values are some subclass of NSObject

NSDictionary 不会在这里工作(枚举不符合 NSCopying )。

我可以在这里使用 CFDictionaryRef ,但我想知道是否有其他方法

I could perhaps use a CFDictionaryRef here, but I'd like to know if is there any other way to achieve this.

推荐答案

由于枚举是整数,因此可以将枚举包装在NSNumber中。当你向/从地图添加/返回某些东西时,你将枚举传递给NSNumber构造函数...

Since enums are integers, you can wrap the enum in an NSNumber. When you add/retreive something to/from the map, you pass the enum to the NSNumber constructor...

假设你有一个枚举... ...

Assuming you've got an enum like...

enum ETest {
    FOO, BAR
};

你可以在这样的NSDictionary中使用它...

You can use it in an NSDictionary like this...

NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setObject: @"Foo!" forKey:[NSNumber numberWithInt: FOO]];
NSLog(@"getting value for FOO -> %@", 
      [dict objectForKey: [NSNumber numberWithInt: FOO]]);  
[dict release]; 

这篇关于Cocoa:使用枚举键的字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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