具有静态枚举和字典的常量文件

时间:2018-04-20 18:06:15

标签: ios objective-c

我是Objective C的新手(来自Java世界)。

我试图创建一个Constants Header文件,该文件可以允许Classes使用静态常量,静态枚举和静态字典。

这里是Constants.h的伪代码

extern NSString* const WelcomeMessage;

typedef enum {
RED,
GREEN,
ORANGE
} Color;

//Use the above Color Enum values as keys to map each color to a message String.

NSDictionary *colorMapper= [NSDictionary dictionaryWithObjectsAndKeys:
    RED, @"Excellent choice. Red is the color of love",
    GREEN, @"Can't go wrong with Green. Green is associated with Nature",
    ORANGE, @"The color is as sweet as a juicy Floridian Orange"
];

Constants.m

...

- (void)printColor:(Color) color
{
  NSLog(@"%@", [colorMapper objectForKey:color]);

}

我试图找出如何正确声明静态常量,静态枚举和静态字典,其中键为Color Enum,类型为String类型。这是可行的(可以使用静态枚举和带枚举的字典作为键)吗?如果没有其他方法来实现这种行为?

1 个答案:

答案 0 :(得分:1)

[所有代码直接输入答案,预计拼写错误。]

(目标 - )C对在常量初始化中可以使用的表达式和类型有限制;这些包括基本类型(整数,字符等),字符串(包括C和NSString),但不包括NSDictionary值。

但是对于Objective-C,当包含代码的二进制文件(应用程序或框架)加载时,会调用+load方法。此方法在任何+initialize方法之前运行。使用此功能可以实现您的目标,从Constants.h

开始
extern NSString * const WelcomeMessage;

typedef enum {
   RED,
   GREEN,
   ORANGE
} Color;

extern NSDictionary * colorMapper;

并在Constants.m中定义一个类,只是为了包含+load来初始化NSDictionary

#import "Constants.h"

NSString * const WelcomeMessage = @"...";

NSDictionary * colorMapper;

// pick a hard to type name...
@interface Private_Hidden_Class_To_Init_Dictionary_
@end

@class Private_Hidden_Class_To_Init_Dictionary_

+ (void) load // will execute automatically when this file is loaded
{
   colorMapper = 
      @{ @(RED) : @"Excellent choice. Red is the color of love",
         @(GREEN) : @"Can't go wrong with Green. Green is associated with Nature",
         @(ORANGE) : @"The color is as sweet as a juicy Floridian Orange"
      };
}

@end

此代码使用@{ ... } Objective-C字面语法进行词典。另请注意,与代码不同,使用@(RED)等作为键。 NSDictionary的键必须是对象,@(RED)是Objective-C文字,它生成NSNumber类型的对象。

(注意:可能有一个属性可以附加到C函数以赋予它相同的run-at-load语义,但是我没有找到Clang文档中列出的一个。使用C函数会删除对课程的需要。)

HTH