0

在objective-c中创建一个类似于类属性的常量的方法是什么?(例如 classA.KEY_FOR_ITEM1)

那就是我看到有关如何在此处创建常量的建议http://stackoverflow.com/questions/538996/constants-in-objective-c 然而,这种方法似乎创建了一个全局常量并且可以在任何地方引用。

我对必须使用类名来指定上下文的常量更感兴趣。假设你有一个 Event 对象,那么你可以指定 EventType 常量(例如 EVENTTYPE_DIRECT)

  EventType.EVENTTYPE_DIRECT

所以问题是 *.h 和 *.m 代码段是什么

4

2 回答 2

3

在我看来,您和我一样来自 Java 风格的语言背景(对不起,如果我在这里猜错了)。我也想知道这一点,然后我注意到Apple如何定义枚举并使用它们来定义您所描述的常量。

让我们以虚构类Event为例:

在头文件中,您要定义一个新的枚举:

typedef enum {

    kEventType_EventName1,
    kEventType_EventName2,
    kEventType_EventName3

}EventType;  //this is the name of the new type

where EventName1etc 被替换为您想要的事件的实际名称(即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!

于 2011-12-04T07:15:01.753 回答
1

It's not clear what you are trying to do here - is the "constant" to be used to substitute for a property in the class, or is Class1.CONSTANT supposed to return a different value to Class2.CONSTANT?

Either way it seems like constants are not the right approach here. In the former case, simply use the real property accessor - if you decide to change this, the refactoring tools make that trivial.

In the latter case, each class could have a class method with your required name, which returns the value appropriate for the class. Again, if this changes the refactoring tools will help.

Adding constants to this mix seems unnecessary and introduces an extra dependency (the maintenance of the constants) without any real benefit.

于 2011-12-04T07:29:23.243 回答