
UITableView中枚舉類型例子.png
NS_ENUM
從iOS6開始,蘋果開始使用NS_ENUM和 NS_OPTIONS宏替代原來的C風(fēng)格的enum進(jìn)行枚舉類型的定義。
typedef NS_ENUM(NSInteger, UITableViewCellStyle) {
UITableViewCellStyleDefault,
UITableViewCellStyleValue1,
UITableViewCellStyleValue2,
UITableViewCellStyleSubtitle
};
NS_OPTIONS
通過按位掩碼的方式也可以進(jìn)行枚舉類型的定義
typedef NS_OPTIONS(NSUInteger, UITableViewCellStateMask) {
UITableViewCellStateDefaultMask = 0,
UITableViewCellStateShowingEditControlMask = 1 << 0,
UITableViewCellStateShowingDeleteConfirmationMask = 1 << 1
};
兩者的區(qū)別
- NS_ENUM枚舉項(xiàng)的值為NSInteger,NS_OPTIONS枚舉項(xiàng)的值為NSUInteger
- NS_ENUM定義通用枚舉,NS_OPTIONS定義位移枚舉
位移枚舉即是在你需要的地方可以同時(shí)存在多個(gè)枚舉值如這樣:
UISwipeGestureRecognizer *swipeGR = [[UISwipeGestureRecognizer alloc] init];
swipeGR.direction = UISwipeGestureRecognizerDirectionUp | UISwipeGestureRecognizerDirectionDown;
而NS_ENUM定義的枚舉不能幾個(gè)枚舉項(xiàng)同時(shí)存在,只能選擇其中一項(xiàng),像這樣:
NSMutableParagraphStyle *paragraph = [[NSMutableParagraphStyle alloc] init];
paragraph.baseWritingDirection = NSWritingDirectionLeftToRight;
PS : 判斷一個(gè)枚舉類型的變量為某個(gè)值的時(shí)候,不用 == ,而是用按位與:
if (swipeGR.direction & UISwipeGestureRecognizerDirectionUp)
結(jié)論:只要枚舉值需要用到按位或(2個(gè)及以上枚舉值可多個(gè)存在)就使用NS_OPTIONS,否則使用NS_ENUM