What would be the way to create a constant in objective-c that is called like a class property? (e.g. classA.KEY_FOR_ITEM1)
That is I see the advice re how to create a constant here http://stackoverflow.com/questions/538996/constants-in-objective-c This approach approach however seems to create a constant that is global and can be referenced anywhere.
I was more interested in a constant that you had to specify the context by using the class name too. So say you had an Event object, then you could have EventType constants specified (e.g. EVENTTYPE_DIRECT)
EventType.EVENTTYPE_DIRECT
So the question is what would the *.h and *.m code segments be for this
Sounds to me like you’re coming from a Java-style language background, as do I (sorry if I’m guessing wrong here). I wondered about this too for a while, and then I noticed how Apple defines enums and uses them to define constants like you’re describing.
Let’s use the imaginary class
Eventas an example:In the header file, you want to define a new enum:
where
EventName1etc, is replaced with the actual names of the events you want (ie.kEventType_Direct.Any other class that needs to see these event types just needs to import your Event.h file:
Then you can use
EventTypeas you would any other variable type (bearing in mind that it is not an NSObject, and does cannot be retained, released, etc – you would treat it like any other C type: int, float, etc)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:
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!