如何使用`typedef NS_ENUM`在一个.h文件中定义几个变量类型 [英] How to define several variable types in one .h file using `typedef NS_ENUM`
问题描述
我已经使用 typedef NS_ENUM
来重组旧代码中的数据常量。使用方法在这里找到每个 typedef
在单个 .h
文件,可以导入项目中的任何类。 .h文件的内容包装在编译器的消息中。这对 int
变量很好。
I have used typedef NS_ENUM
to reorganise data constants in old code. Using an approach found here every typedef
is declared in a single .h
file that can be imported to any class in the project. Content of the .h file is wrapped in a message to the compiler. This works nicely for int
variables.
MYCharacterType.h
#ifndef MYCharacterType_h
#define MYCharacterType_h
typedef NS_ENUM(NSInteger, MARGIN)
{
MARGIN_Top = 10,
MARGIN_Side = 10,
MARGIN_PanelBaseLine = 1
};
...
#endif /* SatGamEnumType_h */
但Xcode抱怨当我尝试包含 float
变量
But Xcode complains when I try to include float
variables
非积分类型'NSNumber'是一个无效的底层类型'
"Non-Integral type ’NSNumber’ is an invalid underlying type’
例如
typedef NS_ENUM(NSNumber, LINE_WIDTH) {
LINE_WIDTH_Large = 1.5,
LINE_WIDTH_Medium = 1.0,
LINE_WIDTH_Small = 0.5,
LINE_WIDTH_Hairline = 0.25
};
我收到相同的消息,无论我是否使用 NSValue
或 NSNumber
所以我怀疑 typedef NS_ENUM
不是定义 float
变量(或至少我使用的方式)。
I get the same message whether I use NSValue
or NSNumber
so I suspect typedef NS_ENUM
is not the way to define float
variables (or at least the way I am using it).
在这个答案中的方法只会让我做我已经在一个文件中组织了一些文件,但并没有提供一种方法来重组同一个文件中的 float
变量。有人可以解释如何做到这一点,所以所有变量都定义在一个 .h
文件中,不管其类型如何?谢谢
The approach in this answer would only allow me to do what I have already organised in one file but does not offer a way to reorganise float
variables in the same file. Could someone please explain how to do this so all variables are defined in one .h
file regardless of their type ? Thanks
解决方案
这是由rmaddy回答,我以不同的方式接近问题。
This was answered by rmaddy after I approached the question differently.
推荐答案
在一个 .h
中定义不同的枚举..就像添加一个文件。
Defining different enums in one .h
.. like just add it one file.
typedef NS_ENUM(NSInteger, MARGIN)
{
MARGIN_Top = 10,
MARGIN_Side = 10,
MARGIN_PanelBaseLine = 1
};
typedef NS_ENUM(long, ENUM_2)
{
ENUM_2_1 = 10,
ENUM_2_2 = 20,
ENUM_2_3 = 30,
};
typedef NS_ENUM(long, ENUM_3)
{
ENUM_3_1 = 10,
ENUM_3_2 = 20,
ENUM_3_3 = 30,
};
// And so on as many as you want
而你的第二个问题,枚举只能是整体数据类型,例如 int
, long
, long long
, unsigned int
, short
etc ...你不能使用任何非 - 像 float
或 double
或甚至没有任何客观c类型的整体类型。
And your second question, Enums can only be of the integral data types like, int
, long
, long long
, unsigned int
, short
etc... You can't use any Non-Integral types like float
or double
or not even any objective c types.
您可以为此浮动值执行枚举映射,如 https:// stackoverflow .com / a / 8867169/1825618
You can do enum mapping for float values like this https://stackoverflow.com/a/8867169/1825618
这篇关于如何使用`typedef NS_ENUM`在一个.h文件中定义几个变量类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!