Objective C global constants with case/switch
Is there any way to use global int constants in Objective C that work in a case/switch statement? The technique here (http://stackoverflow.com/questions/538996/constants-in-objective-c) lets me access the constants everywhere, but does not let me put them into a switch statement.
in .h
FOUNDATION_EXPORT const int UNIT_IDLE;
FOUNDATION_EXPORT const int UNIT_DEFEND;
in .m
int const UNIT_IDLE = 0;
int const UNIT_DEFEND = 1;
Error is "Expression is not an integer constant expression"
I usually use enumerations with typedef statements when using constants which I will use in a switch statement.
For example, this would be in a shared .h file such as ProjectEnums.h:
enum my_custom_unit
{
MyCustomUnitIdle = 1,
MyCustomUnitDefend = 2
};
typedef enum my_custom_unit MyCustomUnit;
I can then use code similar to the following switch statement in my .c, .m, .cpp files:
#import "ProjectEnums.h"
- (void) useUnit:(MyCustomUnit)unit
{
switch(unit)
{
case MyCustomUnitIdle:
/* do something */
break;
case MyCustomUnitDefend:
/* do something else */
break;
default:
/* do some default thing for unknown unit */
break;
};
return;
};
This also allows the compiler to verify the data being passed to the method and used within the switch statement at compile time.
I think your best option is using enum types
. Just declare a type in your header file and then you are ready to use it in a switch statement.
class.h
typedef enum{
kEditGameModeNewGame = 0,
kEditGameModeEdit = 1
}eEditGameMode;
class.m
eEditGameMode mode = kEditGameModeEdit;
switch (mode) {
case kEditGameModeEdit:
// ...
break;
case kEditGameModeNewGame:
// ...
break;
default:
break;
}
Good luck!
Official guideline says you should use "enumerations for groups of related constants that have integer values." That may solve your problem and improve code.
链接地址: http://www.djcxy.com/p/84438.html上一篇: Java:不能在交换机中处理一个案例