0

I am a newbie in objective c so probably this question is stupid. I need a class where are only constants. Let's say I have many constants defined like this:

uint8_t const ONE = 1

In my app a have 20 constants and I want to access to its values from many places (classes). In C# I would do that with class with constants and access to them statically:

Constants.ONE;

But in Objective C it is a problem to me to do that. I know I can put constants to some header file and then import it to classes but there is a risk of duplication.

For example a have a class A, B, C. In class A I import class B and C. Each of this classes need access to constants but I can´t import header file to each of them (if class B has constants and A also, constants are duplicated).

DanielH
  • 953
  • 10
  • 30
  • 1
    The only caveat I'd add to the accepted answer there is since Objective-C has no namespaces, you need to name your constants something that will likely be unique - such as `CBVSomeControllerParameterConstant` - see all the various constants in UIKit and Foundation for inspiration on naming. – Carl Veazey Nov 07 '13 at 16:29

1 Answers1

1

Objective-C is a superset of C, this means that you can use any C feature inside your code. Now IIRC C doesn't support constant in structs directly but you can define a constant struct and initialize it directly through C99 designated initializers lists (just to maintain readability), something like:

struct constants
{
  const int INT_VALUE;
  const char* STRING_VALUE;
} const Constants = {
  .INT_VALUE = 10,
  .STRING_VALUE = "Foobar"
};

...
Constants.INT_VALUE
...
Jack
  • 131,802
  • 30
  • 241
  • 343
  • But still I have to import a file with struct to my class. And If I import to that class another class with iported struct, I have a duplicity of constants in my class... – DanielH Nov 08 '13 at 08:31