【问题标题】:Public static variable in iOSiOS中的公共静态变量
【发布时间】:2015-03-19 20:12:08
【问题描述】:
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。有可能吗?

【问题讨论】:

标签: ios objective-c public


【解决方案1】:

如果您想在课堂上使用它,请在您的 .m 文件中试试这个。

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

如果您希望它是全局变量,您应该在.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;}

【讨论】:

  • 如果在.h文件中标记为extern,则必须在.m文件中删除static,否则无法编译。
【解决方案2】:

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

static const NSInteger DELETE = -1;

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

NSInteger test = DELETE;

这是最接近 Java 代码的地方...

【讨论】:

    猜你喜欢
    • 2011-09-23
    • 2014-03-15
    • 2015-12-02
    • 2012-02-03
    • 2015-04-07
    • 1970-01-01
    • 1970-01-01
    • 2011-07-12
    相关资源
    最近更新 更多