开发者

How do a make a kMyCustomName = 1 and kMyOtherCustomName = 2 global in my code? [duplicate]

开发者 https://www.devze.com 2023-03-24 12:10 出处:网络
This question already has answers here: Constants in Objective-C 开发者_开发技巧 (14 answers) Closed 9 years ago.
This question already has answers here: Constants in Objective-C 开发者_开发技巧 (14 answers) Closed 9 years ago.

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?


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.


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


#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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号