objective-c - 带有 BOOL 标志的应用程序状态

标签 objective-c c boolean state flags

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

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

代码:

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

此外,这很糟糕,因为我一次可以选择 2 个状态。

附言 我发现现代的和更苹果的方式。在下面回答。

最佳答案

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

注意这将为您提供最多 64 种不同的状态(在大多数平台上)。如果您需要更多可能的状态,此解决方案将不起作用。

处理此方案需要您完全理解并安全地处理 boolean 代数。

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

关于objective-c - 带有 BOOL 标志的应用程序状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8956364/

相关文章:

iOS 动态改变 rootViewController

objective-c - Objective C 从另一个应用程序中检索数据

c - 我正在尝试使用 C 程序查找单词的拼字游戏值

python - 用于有条件减去现有值的 Numpy boolean 索引掩码

python - 检查数字是否为素数的函数

ios - AFHTTPSessionManager 忽略 HTTPMaximumConnectionsPerHost

ios - 从包含对象名称的字符串访问对象的属性

c - DSP 库 - RFFT - 奇怪的结果

c - 我的 Checkprime.c 程序有什么问题?

objective-c - 这个 boolean 比较是否正确?