我想知道,是否可以检索枚举中所有项目的列表?
例如我定义了:
typedef enum YouJustUnlocked {
Unlocked_A,
Unlocked_B,
//etc... many more
Unlocked_Nothing,
}YouJustUnlocked;
有没有办法在新定义的枚举类型YouJustUnlocked中检索所有“项目”(不准确的单词)的列表?
Objective-C支持吗?
我想要像:
NSArray * array = [YouJustUnlocked returnAllItemsInWrapperObjectForm];
YouJustUnlocked item = (YouJustUnlocked) [array objectAtIndex:0];
//Assuming that array will contain some sort of wrapper object (like NSInteger)
答案 0 :(得分:2)
不,如果不使用等效的描述列表,那是不可能的:
YourClass.h:
typedef enum YouJustUnlocked {
Unlocked_A,
Unlocked_B,
//etc... many more
Unlocked_Nothing,
// Add this:
Num_Unlocked
}YouJustUnlocked;
YourClass.m:
static NSString *_youJustUnlockedDesc[Num_Unlocked] = {
@"Unlocked_A",
@"Unlocked_B",
//etc... many more
@"Unlocked_Nothing",
}
@implementation YourClass
+ (NSString *)youHaveUnlockedDesc:(YouJustUnlocked)yju {
NSAssert(yju < Num_Unlocked, @"Out-of-range");
return _youJustUnlockedDesc[yju];
}
...
@end
注意:
typedef
将位于头文件中,而description数组将位于实现文件中。Unlocked_Nothing
通常应该是enum
的第一个元素。答案 1 :(得分:0)
如果 您的枚举值是连续的,您可以这样做:
typedef enum {
eUnlockedNothing = 0,
eUnlockedA, /* inferred that this is 1 */
eUnlockedB,
eUnlockedMax
} YouJustUnlocked;
NSMutableArray *array = [NSMutableArray array];
for (int i = eUnlockedNothing + 1; i < eUnlockedMax; i++)
{
[array addObject:@(eUnlockedNothing + i)];
}
YouJustUnlocked item = (YouJustUnlocked) [[array objectAtIndex:0] intValue]; //enums are default ints.
结果是您有一个可以通过索引访问的枚举值数组。此数组不包含eUnlockedNothing
或eUnlockedMax
值。