在我看来,您和我一样来自 Java 风格的语言背景(对不起,如果我在这里猜错了)。我也想知道这一点,然后我注意到Apple如何定义枚举并使用它们来定义您所描述的常量。
让我们以虚构类Event
为例:
在头文件中,您要定义一个新的枚举:
typedef enum {
kEventType_EventName1,
kEventType_EventName2,
kEventType_EventName3
}EventType; //this is the name of the new type
where EventName1
etc 被替换为您想要的事件的实际名称(即kEventType_Direct
。
需要查看这些事件类型的任何其他类只需要导入您的 Event.h 文件:
#import "Event.h"
然后您可以EventType
像使用任何其他变量类型一样使用它(请记住,它不是 NSObject,并且不能保留、释放等 - 您可以像对待任何其他 C 类型一样对待它:int、float 等)
You can even have EventType typed variables as members of other classes, so long as those classes import your Event.h header.
But that allows you to do things like this:
-(void) handleEventOfType: (EventType) evtType {
switch(evtType) {
case kEventType_EventType1 :
//stuff here
break;
//etc...
}
}
That's the best way I've seen to do it so far, and seems to be the way that is generally practiced abroad (at least in most of the projects that I've seen). Anyway, hope that helps!