Iphone 如何在我的代码中使kMyCustomName=1和kMyOtherCustomName=2成为全局的?
我有以下功能:Iphone 如何在我的代码中使kMyCustomName=1和kMyOtherCustomName=2成为全局的?,iphone,objective-c,xcode,cocoa-touch,ios4,Iphone,Objective C,Xcode,Cocoa Touch,Ios4,我有以下功能: + (int)isCorrectOnServer:(int)num { // some code performs here... if (this) { result = 2; } else if (this2) { result = 1; } else { result = 0; } return result; } 我希望它像这样返回: + (int)isCorrectOnServer:(int)num { // some code per
+ (int)isCorrectOnServer:(int)num {
// some code performs here...
if (this)
{
result = 2;
}
else if (this2)
{
result = 1;
}
else
{
result = 0;
}
return result; }
我希望它像这样返回:
+ (int)isCorrectOnServer:(int)num {
// some code performs here...
if (this)
{
result = kOnServer;
}
else if (this2)
{
result = kWrongType;
}
else
{
result = kNotOnServer;
}
return result; }
因此,在我的代码中的任何地方,我都可以调用:
if ([Helper isCorrectOnServer:276872] == kOnServer)
使我的代码更干净,结果不显示0、1或2。执行此操作的最佳方法是什么?将内容添加到项目的前缀头文件中,通常名为prefix.pch 或者,更干净的解决方案是创建一个contants文件,如contants.h,并将该文件包含在前缀头文件中 前缀.pch
#include Contants.h
Contants.h
#define kMyCustomName 1
#define kMyOtherCustomName 2
在它们将被使用的范围内,正如Felipe Sabino所说,要使它们真正全球化,它们应该在前缀标题中。如果有疑问,看看苹果会怎么做。查看UIKit中的任何头文件,您将看到枚举用于具有有限数量选项的任何类型的值 只需将其放入头文件:
typedef enum {
MYCustomTypeOne,
MYCustomTypeTwo,
MyCustomTypeEtcetera
} MYCustomType;
在定义上使用适当的枚举允许您定义如下方法:
+(BOOL)isCustomTypeCorrectOnServer:(MYCustomType)type;
然后,参数可以通过Xcode自动完成。例如,如果您在开关案例中使用该值,编译器可以做出更好的假设。我将向您推荐一个已经编写好的令人敬畏的答案:如何通过整个应用程序而不仅仅是在单个.h文件中实现全局性?是否可以以任何方式将其放在Constants.h文件中?您可以将其放在任何位置,任何头文件(或实现文件,对于私有枚举)中。从前缀头文件导入的任何头文件(查找扩展名为
pch
的文件)都可以在任何地方访问,而无需显式导入定义枚举的头文件。
+(BOOL)isCustomTypeCorrectOnServer:(MYCustomType)type;