iOS中的公共静态变量

时间:2015-01-21 10:37:15

标签: ios objective-c public

public class CommandType {
    public static final int DELETE = -1;
}

//Class B - Access from class B here
CommandType.DELETE

如果我正在使用

//ClassA.h
extern int  const kMyConstant;

//ClassA.m
int  const kMyConstant = @"my constant"; 

switch (messagetype) {
                case kMyConstant: //Can't set const value here
    }

我需要将其转换为objectiveC。有可能吗?请帮帮我。

先谢谢

2 个答案:

答案 0 :(得分:2)

如果要在班级中使用此功能,请在.m文件中尝试此操作。

#import "yourimport";
static const NSInteger DELETE = -1;
@implementation YourClass

如果你想要它是全局变量你应该在in.h文件中执行此操作

extern NSInteger *const DELETE;

为了做到这一点

//ClassA.h
extern int  const kMyConstant;

//ClassA.m
int  const kMyConstant = @"my constant"; 

switch (messagetype) {
                case kMyConstant: //Can't set const value here
    }

您应该在.h:

中创建ENUM
#import <AVFoundation/AVFoundation.h> 
typedef NS_ENUM(NSInteger, YourType) {
    YourTypeConstant1                      = 0,
    YourTypeConstant2,
};

@interface YourViewController : ViewController

然后:

NSNumber *number = @(YourTypeConstant1);
switch (number) {

        case YourTypeConstant1:

            //your code
            break;

        case YourTypeConstant1:

           //your code
           break;
default:
//your default code
break;}

答案 1 :(得分:1)

处理整数常量的最佳方法是在.h文件中声明它:

static const NSInteger DELETE = -1;

然后,导入.h文件的每个文件(在您的情况下,例如B类)都能够访问常量,例如:

NSInteger test = DELETE;

这是你最接近java代码...