开发者

Objective C: way to check for enabled flags

开发者 https://www.devze.com 2023-04-08 08:33 出处:网络
I am using bitflag to enable/disable some functionality in my code. I have following enum. typedef enum function {

I am using bitflag to enable/disable some functionality in my code. I have following enum.

typedef enum function {
    function1 = 1 << 0,
    function2 = 1 << 1,
    function3 = 1 << 2,
    function4 = 1 << 3
};

I know that I need to use following code to check which flag has been enabled.

if((flags & function1) == funct开发者_StackOverflow社区ion1)
{
    // do some action
}

In my enum, number of flags is large and to check every flag, I need to have that many "if" condition checks. Is there any way which can minimize the number of if statements required? I am new to objective C and looking to implement it in objective C. Thanks in advance.


Yes, combine the flags via a bitwise or:

if (flags & (function1 | function2 | function3 | function4))
{
  // any of the flags has been set
}

Moreover, to check for a particular flag you don't need the part == function1, flags & function1 is sufficient as it will evaluate either to zero or function1.

0

精彩评论

暂无评论...
验证码 换一张
取 消