There is a lot of type checking ways. You can define as constant strings to check later on, or you could use
enum for convenient way (this one could be used the most) … but there is one way of type checking, that’s is using
Bitmask. This article will lead you digging into how to use bitmask in Objective C.
As we easily can see,
Apple uses a lot of bitmask in the SDKs, for example:
We will make our own example, let’s see:
We actually used
Bitwise operator, called
Bit shift in this case, because in this operation, the digits are moved, or shifted. With our example, the digits are moved to left. For more info you could check this out, talking about Bitwise operations: https://en.wikipedia.org/wiki/Bitwise_operation
So now we present the example in Binary:
HOW TO USE?
1. Use | (Bitwise OR) for setting on or turning on a flag.
If you want to add more flag in existing flags:
teams |= PLandayEngineerTeam_Frontend;
2. Use & (Bitwise AND) for checking the state of a flag.
bitwise operators are good for normally work, but there is further more. Let’s continue.
3. Use ~ (Bitwise NOT) for Deleting a flag.
teams &= ~PLandayEngineerTeam_Backend;
4. Use ^ (Bitwise XOR) for toggling a flag (turns it on if it was off, or off if it was on), rarely used.
teams ^= PLandayEngineerTeam_Backend;
Why using it?
- Save space: instead of using NSInteger could takes 32 bits or 64 bits, we alternatively use Bit Flag which is few bits.
- In help of understanding RGBA color: http://www.learncpp.com/cpp-tutorial/3-8a-bit-flags-and-bit-masks/
Well, so like them or not, in my opinion, these are used a lot by Apple, so it would be benefit if we’re familiar with them. And one more thing, life will be excited to know things.
References: * http://www.vipan.com/htdocs/bitwisehelp.html * https://www.bignerdranch.com/blog/smooth-bitwise-operator/ * http://nshipster.com/ns_enum-ns_options/