2012-05-10 55 views
0

大家好我有一个枚举类型,包含我的错误代码。NSArray中枚举的所有值?

的问题是,它们不是连续的,即

enum{ 
    ErrorCode1    = 1, 
    ErrorCode2    = 4, 
    ErrorCode3    = 74 
}; typedef NSInteger MyErroCodes; 

也有可能会是50码+,所以我真的不希望有复制的数据或做手工,这是我”迄今为止在我的搜索中已经看到。任何帮助将不胜感激。

+2

为什么你需要把它们放在一个数组中? – JeremyP

回答

3

enum构造仅在编译时存在。在运行时,您的MyErrorCodes实例是纯整数,而ErrorCodeN值只是纯整数常量。没有办法在运行时从你的枚举中提取元数据(好吧,也许有调试信息等,但你不想去那里...)。

我建议:

  • 创建一个小脚本(Python和Perl或诸如此类的东西)来生成映射的数字代码字符串值的函数。在Xcode中,如果你真的想要的话,你甚至可以在编译阶段运行代码生成器。
  • 在编译期间使用元编程或预处理器宏来生成这些函数。这需要一些想法,但它可以完成。
0

这是使用包括其中包含所有一些体内使用宏的值和有时候的文件的通常完成:

ErrorCode_enum.h

MON_ENUM_VALUE(ErrorCode1, 1) 
MON_ENUM_VALUE(ErrorCode2, 4) 
MON_ENUM_VALUE(ErrorCode3, 74) 

其中MON_ENUM_VALUE将是一个可变宏观扩张。

和你的枚举声明可能采取这种形式:

enum { 
#include "mon_enum_value_begin.h" // defines MON_ENUM_VALUE and such 
#include "ErrorCode_enum.h" 
#include "mon_enum_value_end.h" // undefines MON_ENUM_VALUE and everything else defined in mon_enum_value_begin.h 
}; 
typedef NSInteger MyErroCodes; 

再后来你可能会这样写:

#include "mon_enum_NSNumber_begin.h" // defines MON_ENUM_VALUE and such 
#include "ErrorCode_enum.h" 
#include "mon_enum_NSNumber_end.h" // undefines MON_ENUM_VALUE and… 

#include "mon_enum_NSError_begin.h" // defines MON_ENUM_VALUE and such 
#include "ErrorCode_enum.h" 
#include "mon_enum_NSError_end.h" // undefines MON_ENUM_VALUE and… 

这可能会增加或stringize这些标记和值到其他类型。个人而言,我认为宏是粗略的,只是采取替代方法(其中,可以肯定的是,对编写可能更单调)。