Understand about bitwise operator and comparing them
Summary (For tho who want the tl;dr version, you may skip to the question below):
I've just gone through this problem: Comparing UIDeviceOrienation and UIInterfaceOrientation. After that, I took a look at how bitwise work (because I've seen them sometimes, but not really understand how they work.)
So, I've taken a research about What's bitwise operator, How enum in objective-c work with bit, How to use enum that's in bit.
(TL;DR) Now, here's my question:
Let's say, I want to check if my UIInterfaceOrientation = Landscape (Left | Right) should I use it like this:
[UIApplication sharedApplication].statusBarOrientation ==
(UIInterfaceOrientationLandscapeLeft |
UIInterfaceOrientationLandscapeRight)
OR
[UIApplication sharedApplication].statusBarOrientation &
(UIInterfaceOrientationLandscapeLeft |
UIInterfaceOrientationLandscapeRight)
Should they give the same result? Or different? Which one is more appropriate?
(In my simple mind, if it's not wrong then the second one is more appropriate).
BONUS QUESTION
Other than enums, is there anywhere else where I can use bitwise, bitshift operator effectively?
It depends on what you want to do:
The first approach means:
UIInterfaceOrientationLandscapeLeft AND UIInterfaceOrientationLandscapeRight is set and no other options (even with different semantics) are set.
This will never be true, because UIInterfaceOrientationLandscapeLeft and UIInterfaceOrientationLandscapeRight are mutually exclusive.
The second approach means:
UIInterfaceOrientationLandscapeLeft OR UIInterfaceOrientationLandscapeRight is set and other options are ignored.
Likely this is what you want to do.
But you should really read something about bit operations. There are a mass of tutorials in the web. You can use every tutorial dealing with C, too.
Bonus Q:
a. What is the bonus I get?
b. Yes, you do not need an enum
to declare constants. You can simply do that with global constants:
const int Option1 = 1 << 0;
const int Option2 = 1 << 1;
…
c. Beside this you can do some arithmetic magic with bit operations, like dividing and multiplying with powers of 2, checking, whether a number is even or odd, …
链接地址: http://www.djcxy.com/p/72666.html上一篇: 真实世界的按位运算符用例
下一篇: 了解按位运算符并对它们进行比较