App States with BOOL flags

余生长醉 提交于 2019-11-29 08:10:54

Use typedef enum to define all possible states using bitmasks.

Note this will give you a maximum of up to 64 different states (on most platforms). If you need more possible states, this solution will not work.

Handling this scheme will require you to fully understand and safely handle boolean algebra.

//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
}
Rok Jarc

You can always use a byte (unsigned char) size variable using its' bits as flags (each bit acts as one BOOL flag).

Good instructions to set/clear/toggle/check a bit is here.

Offcourse you'd want to set kind of human readable names for this flags, i.e.:

#define flag1 1
#define flag2 2
#define flag3 4
#define flag4 8
#define flag5 16

Nowadays we have got another option for flags. It is NS_ENUM.

typedef NS_ENUM(NSInteger, UITableViewCellStyle) {
    UITableViewCellStyleDefault,
    UITableViewCellStyleValue1,
    UITableViewCellStyleValue2,
    UITableViewCellStyleSubtitle
};

First arg for type and second for name.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!