具有BOOL标志的应用程序状态

kas*_*tus 3 c flags state boolean objective-c

我的应用程序中有5个状态,我使用BOOL标记来标记它们.但这并不简单,因为当我想改变状态时,我必须写5行来改变所有标志.

你能写一些想法或简单的代码来解决这个问题吗?

码:

//need to choose second state
flag1 = false;
flag2 = true;
flag3 = false;
flag4 = false;
flag5 = false;
Run Code Online (Sandbox Code Playgroud)

而且,这很糟糕,因为我可以一次选择2个状态.

PS 我发现现代和更多Apple方式.答案如下.

Til*_*ill 14

用于typedef enum使用位掩码定义所有可能的状态.

请注意,这将为您提供最多64个不同的状态(在大多数平台上).如果您需要更多可能的状态,此解决方案将无法运行.

处理此方案将要求您完全理解并安全地处理布尔代数.

//define all possible states
typedef enum
{
    stateOne = 1 << 0,     // = 1
    stateTwo = 1 << 1,     // = 2
    stateThree = 1 << 2,   // = 4
    stateFour = 1 << 3,    // = 8  
    stateFive = 1 << 4     // = 16
} FiveStateMask;

//declare a state
FiveStateMask state;

//select single state
state = stateOne;         // = 1

//select a mixture of two states
state = stateTwo | stateFive;     // 16 | 2 = 18

//add a state 
state |= stateOne;                // 18 | 1 = 19

//remove stateTwo from our state (if set)
if ((state & stateTwo) == stateTwo)
{
    state ^= stateTwo;           // 19 ^ 2 = 17
}

//check for a single state (while others might also be selected)
if ((state & stateOne) == stateOne)
{
    //stateOne is selected, do something
}

//check for a combination of states (while others might also be selected)
if ((state & (stateOne | stateTwo)) == stateOne | stateTwo)
{
    //stateOne and stateTwo are selected, do something
}

//the previous check is a lot nicer to read when using a mask (again)
FiveStateMask checkMask = stateOne | stateTwo;
if ((state & checkMask) == checkMask)
{
    //stateOne and stateTwo are selected, do something
}
Run Code Online (Sandbox Code Playgroud)

  • `state&= stateTwo`不会删除stateTwo - 它会使stateTwo成为*only*状态.如果你知道你的bitfield中有stateTwo,那么删除它的方法是`state ^ = stateTwo`.(但请注意,如果您在集合中还没有stateTwo,则会添加它.) (2认同)