问题描述
我正在使用Objective-C来开发ios应用程序我在文档中发现枚举具有如下默认值:1 <
我不明白这个默认值
示例:
枚举{
UIDataDetectorTypePhoneNumber = 1<< 0,
UIDataDetectorTypeLink = 1<< 1,
UIDataDetectorTypeAddress = 1<< 2,
UIDataDetectorTypeCalendarEvent = 1<< 3,
UIDataDetectorTypeNone = 0,
UIDataDetectorTypeAll = NSUIntegerMax
};
所以,这个枚举中每个元素的默认值是多少?
谢谢
这是一个具有逐位值或位标志的枚举。每个值都是一个二进制值,其中只有一个位设置为1,所有其他值都设置为0.这样,您可以将值存储为一个整数的位数。
左移运算符
例如,在你的问题中发送的枚举中,第一个值UIDataDetectorTypePhoneNumber,是第二个,UIDataDetectorTypeLink是2,第三个是UIDataDetectorTypeAddress,是4。
将这些值组合为标志,以设置相同的不同位整数:
NSInteger fooIntValue = UIDataDetectorTypePhoneNumber | UIDataDetectorTypeLink;
由于'|'操作是按位的,结果将是一个二进制值... 0011是3.你表明你的变量fooIntValue为两个不同的属性设置了两个标志。
i am using objective-c to develop ios applications
i found in the documentations that enum have default values like this : "1<<0"
i don't understand this default valueexample:
enum {
UIDataDetectorTypePhoneNumber = 1 << 0,
UIDataDetectorTypeLink = 1 << 1,
UIDataDetectorTypeAddress = 1 << 2,
UIDataDetectorTypeCalendarEvent = 1 << 3,
UIDataDetectorTypeNone = 0,
UIDataDetectorTypeAll = NSUIntegerMax
};
so, what is the default value for each element in this enum ?
thanks
That is an enum with bitwise values or bit flags. Each value is an binary value in which only one bit is set to 1 and all the others are set to 0. That way you can store in a value as much flags as bits of an integer number has.
The shift left operator '<<' is a displacement of bits to the left or to the most significant side of the binary number. It is the same that calculating a "* 2" (times two) operation.
For example in the enum you have send in your question, the first value, UIDataDetectorTypePhoneNumber, is 1. The second one, UIDataDetectorTypeLink, is 2 and the third one, UIDataDetectorTypeAddress, is 4.
You combine that values as flags to set some different bits in the same integer:
NSInteger fooIntValue = UIDataDetectorTypePhoneNumber | UIDataDetectorTypeLink;
As '|' operation is bitwise, the result will be a binary value ...0011, that is 3. And you are indicating that your variable fooIntValue has two flags set to true for two different properties.
这篇关于枚举默认值了解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!