使用二进制枚举

89 阅读1分钟

一般情况下,我们定义一段枚举值

typedef NS_ENUM(NSInteger, ObjType) {
    ObjTypeOne,
    ObjTypeTwo,
    ObjTypeThree
};

在实际使用中

@property (nonatomic, assign) ObjType objType;

但是同一时刻它只能表示一个值,即只能

if (objType == ObjTypeOne) {
	// do anything
} else if (objType == ObjTypeTwo) {
	// do anything
}

所以就不能

if (objType == ObjTypeOne) {
	// do anything
}
if (objType == ObjTypeTwo) {
	// do anything
}

这时候,二进制表示的位枚举就可以解决上面的问题了 一个枚举属性,二进制展示是 0000 0000 0000 0000 如果把每一位表示一个枚举值的话,那么,16位的属性就可以表示16个枚举值,32位就可以表示32个枚举值

typedef NS_ENUM(NSInteger, ObjType) {
    ObjTypeOne = 1 << 0,    // 0001
    ObjTypeTwo = 1 << 1,    // 0010
    ObjTypeThree = 1 << 2   // 0100
};

这样的话,一个枚举属性,就可以通过位运算的方式,表示多个枚举值

ObjType objType = ObjTypeOne | ObjTypeTwo | ObjTypeThree; // 0111

ObjType objType2 = 0;
objType2 |= ObjTypeOne;   // 0001
objType2 |= ObjTypeTwo;   // 0011
objType2 |= OjbTypeThree; // 0111

在使用的时候,判断是否包含某个枚举

if (objType & ObjTypeOne) {  // 0111 & 0001 = 0001 = true
	// do anything
}
if (objType & ObjTypeTwo) {  // 0111 & 0010 = 0010 = true
	// do anything
}

如何在已经组合后的枚举属性中,移除掉某个枚举项

objType &= ~ObjTypeOne    // 0111 & ~(0001) = 0111 & 1110 = 0110