有趣的位掩码
有很多类型检查方法。 您可以将其定义为常量字符串以供日后检查,也可以使用enum进行便捷的方式(这种方式最多可以使用)…但是有一种类型检查的方法,即使用Bitmask 。 本文将引导您深入了解如何在Objective C中使用Bitmask 。
我们可以很容易地看到,Apple在SDK中使用了大量Bitmask ,例如: UIViewAutoresizing , UIInterfaceOrientation …
我们将创建自己的示例,让我们看看:
typedef NS_OPTIONS (NSUInteger,PLandayEngineerTeam){
PLandayEngineerTeam_Mobile = 1 << 0,
PLandayEngineerTeam_Backend = 1 << 1,
PLandayEngineerTeam_Frontend = 1 << 2
};
我们实际上使用了按位运算符,在这种情况下称为“ 移位” ,因为在此操作中,数字被移动或移位 。 在我们的示例中,数字向左移动。 欲了解更多信息,您可以查看一下有关位操作的信息:https://en.wikipedia.org/wiki/Bitwise_operation
因此,现在我们在Binary中提供示例:
typedef NS_OPTIONS (NSUInteger,PLandayEngineerTeam){
PLandayEngineerTeam_Mobile = 1 << 0, // => 00000001
PLandayEngineerTeam_Backend = 1 << 1, // => 00000010
PLandayEngineerTeam_Frontend = 1 << 2 // => 00000100
};
得到它了?
如何使用?
1.使用| (按位或)以设置或打开标志。
例如:
PLandayEngineerTeam小组= PLandayEngineerTeam_Mobile | PLandayEngineerTeam_Backend;
实际上:
00000001
|
00000010
========
00000011
如果要在现有标志中添加更多标志:
团队| = PLandayEngineerTeam_Frontend;
2.使用&(按位与)检查标志的状态。
if (teams & PLandayEngineerTeam_Mobile == PLandayEngineerTeam_Mobile){
//是行动小组。
}
它解释为:
00000011
和
00000001
========
00000001 // PLandayEngineerTeam_Mobile
两个按位运算符都适合正常工作,但还有更多。 让我们继续。
3.使用〜(按位非)删除标志。
团队&=〜PLandayEngineerTeam_Backend;
其实:
〜PLandayEngineerTeam_Backend //〜00000010 == 11111101
00000011
和
11111101
========
00000001 // == PLandayEngineerTeam_Mobile
4.使用^(按位XOR)切换标志(很少使用时将其打开,如果开启则将其关闭),很少使用。
例如:
团队^ = PLandayEngineerTeam_Backend;
为什么要使用它?
- 节省空间:代替使用NSInteger可以占用32位或64位,我们还可以使用很少的位标志。
- 为了帮助您了解RGBA颜色:http://www.learncpp.com/cpp-tutorial/3-8a-bit-flags-and-bit-masks/
结论
好吧,在我看来,无论是否喜欢它们,Apple都经常使用它们,因此,如果我们熟悉它们,将是有益的。 还有一件事,知道事物会令生活兴奋。