Objective-C : enum like Java (int values and many others for each enum)
In Java, you can make an enum having multiples values. In objective-C, this cannot be done easily. I've read many pages about this but I didn't found anything satisfying that would allow me to use enums by a simple way and to keep the enum declaration and their different values in the same file.
I would like to write something like this in a enums.h :
// ========================================
typedef enum {eRED, eGREEN, eBLUE} ColorEnum;
int colorValues[] = { 0xFF000开发者_如何学运维0, 0x00FF00, 0x0000FF };
NSArray *colorNames = [NSArray arrayWithObjects:@"Red color", @"light green", @"Deep blue", nil];
// ========================================
and be able to use thoses global variables to manage my stuff anywhere like :
int color = colorValues[eRED];
But I don't know how to write this. I have compile errors like "ColorValues" is defines many times. Or if I just use "static", I have many "ColorValues" not used in .m file...
Could you help me ?
You're close - the problem is that you put the definition of your array in the header file, where multiple compilation units end up duplicating it. Put your middle line:
int colorValues[] = { 0xFF0000, 0x00FF00, 0x0000FF };
into one of your .m
files, and change the header to read:
extern int colourValues[];
You'll need to do something similar with colorNames
. Change the header to:
extern NSArray *colorNames;
And then declare the actual object and initialize it in a .m
file.
Your problem has nothing to do with the enum. It's defining variables in a header (rather than just declaring them) that's the problem. Just declare them in the header and move the implementation to an implementation file.
Also, you can't write [NSArray arrayWithObjects…]
outside of a method. Only static initializers (that is, values that can be determined at compile time) are allowed there, whereas messages like that are only resolved at runtime. The solution is to move the assignment into an initialization function (e.g. init
for a singleton or initialize
for a class).
I tryed the following thing that works like a charm :
in enums.h
@interface enums
// here, the enum and its values are in the same place.
typedef enum {eRED, eGREEN, eBLUE} ColorEnum;
#define kColourValue { 0xFF0000, 0x00FF00, 0x0000FF }
extern int colourValues[];
@end
in enums.m
@implementation enums
int colorValues[] = kColourValue;
@end
And you have a perfect Java style implementation of enums in Objective-C. Wow, two weeks of searches....
精彩评论