ios 在 Objective-C 中使用枚举?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1662183/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using enum in Objective-C?
提问by fuzzygoat
Is this the correct (or even a valid way) to use emums in Objective-C? i.e. The menuItem is not used but just defines a list add=1, load=2, list=3 etc.
这是在 Objective-C 中使用 emum 的正确方式(甚至有效方式)吗?即没有使用 menuItem 而是定义了一个列表 add=1、load=2、list=3 等。
enum menuItems {
add = 1 ,
save ,
load ,
list ,
removeAll ,
remove ,
quit
};
int optionSelect;
scanf("%d", &optionSelect);
switch (optionSelect) {
case add:
//...
break;
}
cheers gary
干杯加里
回答by BitDrink
If you want to give a semantic meaning to the enumeration, you can consider to define a customized type and declare the variable "optionSelect" as variable of that type! In code...
如果要给枚举赋予语义,可以考虑定义自定义类型,并将变量“optionSelect”声明为该类型的变量!在代码...
typedef enum menuItems {
add = 1,
save,
load,
list,
removeAll,
remove,
quit} MenuItem;
MenuItem optionSelect;
scanf("%d", &optionSelect);
switch (optionSelect) {
case add:
...
break;
.
.
.
}
That is, almost, the same thing you have written, but from the side of the developer you give a particular meaning to the variable "optionSelect", not just a simple int!
也就是说,几乎与您编写的内容相同,但是从开发人员的角度来看,您为变量“optionSelect”赋予了特定的含义,而不仅仅是一个简单的 int!
回答by Oren Mazor
good explanation, right here: What is a typedef enum in Objective-C?
很好的解释,就在这里:Objective-C 中的 typedef 枚举是什么?
回答by Tommy
In this, the future, it's possibly also helpful to mention NS_ENUM
. You'd use it like:
在这方面,未来,提及NS_ENUM
. 你会像这样使用它:
typedef NS_ENUM(uint16_t, TYEnummedType)
{
TYEnummedType1,
TYEnummedType2
};
That has almost the same effect as a normal enum
and typedef
but explicitly dictates the integer type, which is really helpful if you ever want to pack these things off somewhere, be precise in your struct
alignment, amongst other uses.
这与普通的效果几乎相同enum
,typedef
但明确规定了整数类型,如果您想将这些东西打包到某个地方,精确struct
对齐,以及其他用途,这真的很有帮助。
It was added to the iOS SDK with version 6 and OS X with 10.8 but it's just a C macro and doesn't add anything that you couldn't do with vanilla typedef
and enum
, so there's no backwards compatibility to worry about. It exists only explicitly to tie the two things together.
它被添加到版本 6 的 iOS SDK 和 10.8 的 OS X 中,但它只是一个 C 宏,并没有添加任何你不能用 vanilla typedef
and做的事情enum
,所以没有向后兼容性需要担心。它的存在只是为了将两件事联系在一起。
回答by Boris Vidolov
Your way will work. However, if you would like to use menuItems as a type for variables or parameters, you will need to do a typedef:
你的方法会奏效。但是,如果您想将 menuItems 用作变量或参数的类型,则需要执行 typedef:
typedef enum {add = 1,save,load,list,removeAll,remove,quit} menuItems;
menuItems m = add;
[myobj passItem:m];