Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
665 views
in Technique[技术] by (71.8m points)

objective c - App States with BOOL flags

I've got 5 states in my app, and I use BOOL flags to mark them. But it isn't straightforward, because I have to write 5 lines to change all flags when I want to change state.

Can you write some ideas or simple code to solve this problem?

code:

//need to choose second state
flag1 = false;
flag2 = true;
flag3 = false;
flag4 = false;
flag5 = false;

Also, it's to bad because I can choose 2 states one time.

P.S. I found modern and more Apple-way. Answer below.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...