摘自:http://coffeeandsandwich.com/?p=8
在 iOS 6 和 Mac OS X 10.8 以前,定義枚舉類型的方式如下:
typedef enum the_enum_name{ value_1, value_2, value_3 }the_enum_type_name;
注意:
1. the_enum_name 和 the_enum_type_name 可以是一樣的。
2. 你甚至可以不寫 the_enum_name,只寫 the_enum_type_name。
從iOS6和Mac OS X 10.8開始,蘋果允許你使用新的方式來定義枚舉類型
typedef NS_ENUM(NSInteger, the_enum_type_name){
value_1,
value_2,
value_3
};
NS_ENUM 的第一個參數用來聲明枚舉值們所屬的類型,只能是整形數值類型,一般都是用NSInteger就可以了。第二個參數是枚舉類型的名字。
那么這兩者有什么差別呢?實際上差別不大,不過后者更直觀,而且 NS_ENUM 第二個參數則直接取代了前者的 the_enum_name 和 the_enum_type_name。
另外,枚舉類型還能進行位運算。你可以使用 | 進行或運算或者 & 進行與運算。不過需要用 NS_OPTIONS 來定義,例如iOS里有個 UIViewAutoresizing 的枚舉類型,它的定義就是下面這樣子的:
typedef NS_OPTIONS(NSUInteger, UIViewAutoresizing) { UIViewAutoresizingNone = 0, UIViewAutoresizingFlexibleLeftMargin = 1 << 0, UIViewAutoresizingFlexibleWidth = 1 << 1, UIViewAutoresizingFlexibleRightMargin = 1 << 2, UIViewAutoresizingFlexibleTopMargin = 1 << 3, UIViewAutoresizingFlexibleHeight = 1 << 4, UIViewAutoresizingFlexibleBottomMargin = 1 << 5 };
這個枚舉類型是用來指定當控件的容器(比如說窗口)的大小發生變化時,控件的大小和位置應當如何變化,如果希望這個控件的寬度不變,只改變左右邊距,那么可以這樣負值:
someButton.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;
參考:
What is a typedef enum in Objective-C?
http://stackoverflow.com/questions/707512/what-is-a-typedef-enum-in-objective-c
NS_ENUM & NS_OPTIONS
http://nshipster.com/ns_enum-ns_options/
文章列表