John Lane
John Lane

Reputation: 1132

All values of an enum in an NSArray?

Hi all I have an enum type that holds my error codes.

The problem is that they are not sequential i.e.

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

Also there are maybe 50 codes + so I really wouldn't want to have to duplicate the data or do it manually, which is what I've seen so far in my searches. Any help would be greatly appreciated.

Upvotes: 0

Views: 556

Answers (2)

justin
justin

Reputation: 104698

this is often accomplished using an include of a file which contains all the values within some body and sometimes using macros:

ErrorCode_enum.h

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

where MON_ENUM_VALUE would be a variable macro expansion.

and your enum declaration might take this form:

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;

then later you might write:

#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…

or

#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…

which may add or stringize those tags and values to other types.

Personally, I think the macros are gross, and just take alternate approaches (which, admittedly, may be more tedious to write).

Upvotes: 0

Krumelur
Krumelur

Reputation: 32547

The enum construct only exists at compile time. At run time, your MyErrorCodes instances are plain integers, and the ErrorCodeN values are just plain integer constants. There is no way to extract metadata from your enum in runtime (well, maybe there is in the debug info etc, but you don't want to go there...).

I suggest:

  • Create a small script (Python, Perl or whatnot) to generate functions that map the numeric code to string values. In XCode, you can even run code generators during the compilation phase if you really want.
  • Use metaprogramming or preprocessor macros to generate these functions during compilation. This requires some thought, but it can be done.

Upvotes: 3

Related Questions