1

I have the following function:

+ (int)isCorrectOnServer:(int)num {

// some code performs here...

if (this)
{
    result = 2;
}
else if (this2)
{
    result = 1;
}
else
{
    result = 0;
}

return result; }

I want it to return like this instead:

+ (int)isCorrectOnServer:(int)num {

// some code performs here...

if (this)
{
    result = kOnServer;
}
else if (this2)
{
    result = kWrongType;
}
else
{
    result = kNotOnServer;
}

return result; }

So anywhere in my code I could just call:

if ([Helper isCorrectOnServer:276872] == kOnServer)

to make my code cleaner and not show 0, 1, or 2 as the result. What is the best way to go about doing this?

Ethan Allen
  • 13,099
  • 22
  • 89
  • 175
  • 1
    I will refer you to this awesome answer already written: http://stackoverflow.com/questions/538996/constants-in-objective-c/539191#539191 – MechEthan Jul 29 '11 at 22:44

3 Answers3

3

When in doubt, see what Apple do. Look in any header file in UIKit and you will see enumeration being used for any kind of value with a finite amount of options.

Just put this in the header file:

typedef enum {
    MYCustomTypeOne,
    MYCustomTypeTwo,
    MyCustomTypeEtcetera
} MYCustomType;

Using proper enumerations over defines allow you to do define a method like this:

+(BOOL)isCustomTypeCorrectOnServer:(MYCustomType)type;

Then the argument can be auto completed for you by Xcode. And the compiler can make much better assumptions if you use the value in a switch case for example.

PeyloW
  • 36,308
  • 12
  • 75
  • 98
  • How can I make this global through the entire app, and not just in a single .h file? Can this be put in a Constants.h file in any way? – Ethan Allen Jul 29 '11 at 23:24
  • 1
    You can put it anywhere you want, in any header file (or in an implementation file, for a private enum). Any header file that you import from the prefix header file (look for a file with the `pch` extension) will be accessible everywhere without explicitly importing the header file where you define the enum. – PeyloW Jul 29 '11 at 23:26
0

add the contants to the prefix header file of your project, usually named prefix.pch

Or, an even more clean solution, would be to create a contants file, like contants.h and include this file in your prefix header file.

Prefix.pch

#include Contants.h

Contants.h

#define kMyCustomName 1 
#define kMyOtherCustomName 2
Felipe Sabino
  • 16,519
  • 5
  • 67
  • 110
0
#define kMyCustomName 1
#define kMyOtherCustomName 2

Within the scope that they will be used, as Felipe Sabino said to make them truly global they should be in the prefix header.

JoePasq
  • 5,236
  • 2
  • 30
  • 45