gpt4 book ai didi

ios - NS_ENUM 和 NS_OPTIONS 有什么区别?

转载 作者:IT王子 更新时间:2023-10-29 07:48:14 28 4
gpt4 key购买 nike

我在 Xcode5 中使用 clang 预处理了以下代码。

typedef NS_ENUM(NSInteger, MyStyle) {
MyStyleDefault,
MyStyleCustom
};

typedef NS_OPTIONS(NSInteger, MyOption) {
MyOption1 = 1 << 0,
MyOption2 = 1 << 1,
};

得到这个。

typedef enum MyStyle : NSInteger MyStyle; enum MyStyle : NSInteger {
MyStyleDefault,
MyStyleCustom
};

typedef enum MyOption : NSInteger MyOption; enum MyOption : NSInteger {
MyOption1 = 1 << 0,
MyOption2 = 1 << 1,
};

我知道 NS_OPTIONS 用于位掩码,但有任何技术差异吗?或者这只是为了命名约定?

编辑

根据NS_OPTIONS的定义,应该是为了编译器兼容(尤其是c++编译器)

// In CFAvailability.h
// Enums and Options
#if (__cplusplus && __cplusplus >= 201103L && (__has_extension(cxx_strong_enums) || __has_feature(objc_fixed_enum))) || (!__cplusplus && __has_feature(objc_fixed_enum))
#define CF_ENUM(_type, _name) enum _name : _type _name; enum _name : _type
#if (__cplusplus)
#define CF_OPTIONS(_type, _name) _type _name; enum : _type
#else
#define CF_OPTIONS(_type, _name) enum _name : _type _name; enum _name : _type
#endif
#else
#define CF_ENUM(_type, _name) _type _name; enum
#define CF_OPTIONS(_type, _name) _type _name; enum
#endif

__cplusplus 在 clang 中的值是 199711,不过我无法测试它的确切用途。

最佳答案

枚举和位掩码(选项)之间存在基本区别。您使用枚举来列出独占状态。当多个属性可以同时应用时,使用位掩码。

在这两种情况下,您都使用整数,但您看待它们的方式不同。使用枚举,您可以查看数值,使用位掩码,您可以查看各个位。

typedef NS_ENUM(NSInteger, MyStyle) {
MyStyleDefault,
MyStyleCustom
};

只会代表两种状态。您可以通过测试是否相等来简单地检查它。

switch (style){
case MyStyleDefault:
// int is 0
break;
case MyStyleCustom:
// int is 1
break;
}

而位掩码将代表更多状态。您使用逻辑或按位运算符检查各个位。

typedef NS_OPTIONS(NSInteger, MyOption) {
MyOption1 = 1 << 0, // bits: 0001
MyOption2 = 1 << 1, // bits: 0010
};

if (option & MyOption1){ // last bit is 1
// bits are 0001 or 0011
}
if (option & MyOption2){ // second to last bit is 1
// bits are 0010 or 0011
}
if ((option & MyOption1) && (option & MyOption2)){ // last two bits are 1
// bits are 0011
}

tl;dr 枚举为数字命名。位掩码为位命名。

关于ios - NS_ENUM 和 NS_OPTIONS 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18962925/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com