Bitmask declaration:
Alternatively, to assign absolute values ββ( 1 , 2 , 4 , ...) you can declare bitmasks (as they are called) as follows:
typedef enum : NSUInteger { FileNotDownloaded = (1 << 0),
or using modern ObjC macros NS_OPTIONS / NS_ENUM :
typedef NS_OPTIONS(NSUInteger, DownloadViewStatus) { FileNotDownloaded = (1 << 0),
(see Abizern's answer for more information on the latter)
The concept of a bitmask is to (usually) define each enumeration value with a single set of bits.
Therefore, OR entering two values ββdoes the following:
DownloadViewStatus status = FileNotDownloaded | FileDownloaded;
which is equivalent to:
00000001 // FileNotDownloaded | 00000100 // FileDownloaded ---------- = 00000101 // (FileNotDownloaded | FileDownloaded)
Bitmask comparison:
One thing to keep in mind when checking bitmax:
Exact equality check:
Assume that the status is initialized as follows:
DownloadViewStatus status = FileNotDownloaded | FileDownloaded;
If you want to check if status is FileNotDownloaded , then you can use:
BOOL equals = (status == FileNotDownloaded);
which is equivalent to:
00000101 // (FileNotDownloaded | FileDownloaded) == 00000100 // FileDownloaded ----------- = 00000000 // false
Membership Check:
If you want to check that status just contains FileNotDownloaded , you need to use:
BOOL contains = (status & FileNotDownloaded) != 0; // => true 00000101 // (FileNotDownloaded | FileDownloaded) & 00000100 // FileDownloaded ----------- = 00000100 // FileDownloaded != 00000000 // 0 ----------- = 00000001 // 1 => true
See the subtle difference (and why is your current βifβ expression probably wrong)?