能否用纯布尔逻辑替换位掩码包装器Setter中的if/else语句?
问题:能否用纯布尔逻辑替换
-setActionNotificationPacketReceived:中的if/else语句? 先看现有代码实现:
.h文件代码
typedef NS_OPTIONS(NSUInteger, ActionTrigger) { bitmask0 = 1 << 0, bitmask1 = 1 << 1, ... }; @property (nonatomic) ActionTrigger notificationTrigger; @property (nonatomic) BOOL actionNotificationPacketReceived;
.m文件代码
- (BOOL)actionNotificationPacketReceived { return ((self.notificationTrigger & bitmask0) == bitmask0); } - (void)setActionNotificationPacketReceived:(BOOL)value { if (value) { self.notificationTrigger |= bitmask0; } else { self.notificationTrigger &= ~bitmask0; } }
纯布尔逻辑替换方案
可以通过位运算组合直接实现,不需要if/else判断:
- (void)setActionNotificationPacketReceived:(BOOL)value { // 先清除bitmask0对应位,再根据value决定是否设置该位 self.notificationTrigger = (self.notificationTrigger & ~bitmask0) | (value ? bitmask0 : 0); }
或者利用OC中BOOL本质为整数的特性进一步简化:
- (void)setActionNotificationPacketReceived:(BOOL)value { NSUInteger targetBit = (NSUInteger)value * bitmask0; self.notificationTrigger = (self.notificationTrigger & ~bitmask0) | targetBit; }
编辑补充
最终我使用了如下宏封装该逻辑:
#define OptionSetBool(option, flag, a_bool) ((a_bool) ? ((option) |= flag) : ((option) &= ~flag))
内容的提问来源于stack exchange,提问作者Mojo66
相关产品推荐
相关产品推荐

