美文网首页
iOS 方法参数‘按位或’的原理

iOS 方法参数‘按位或’的原理

作者: 山杨 | 来源:发表于2021-10-14 14:31 被阅读0次
  1. 先以UIViewAutoresizing为例:
typedef NS_OPTIONS(NSUInteger, UIViewAutoresizing) {
    UIViewAutoresizingNone                 = 0,
    UIViewAutoresizingFlexibleLeftMargin   = 1 << 0,
    UIViewAutoresizingFlexibleWidth        = 1 << 1,
    UIViewAutoresizingFlexibleRightMargin  = 1 << 2,
    UIViewAutoresizingFlexibleTopMargin    = 1 << 3,
    UIViewAutoresizingFlexibleHeight       = 1 << 4,
    UIViewAutoresizingFlexibleBottomMargin = 1 << 5
};
1 << 5 -> 0b100000
1 << 4 -> 0b010000
1 << 3 -> 0b001000
1 << 2 -> 0b000100
1 << 1 -> 0b000010
1 << 0 -> 0b000001
  1. 再以AVAudioSessionCategoryOptions为例子
typedef NS_OPTIONS(NSUInteger, AVAudioSessionCategoryOptions) {
    AVAudioSessionCategoryOptionMixWithOthers            = 0x1,
    AVAudioSessionCategoryOptionDuckOthers               = 0x2,
    AVAudioSessionCategoryOptionAllowBluetooth           = 0x4,
    AVAudioSessionCategoryOptionDefaultToSpeaker         = 0x8,
    AVAudioSessionCategoryOptionInterruptSpokenAudioAndMixWithOthers = 0x11,
    AVAudioSessionCategoryOptionAllowBluetoothA2DP  = 0x20,
    AVAudioSessionCategoryOptionAllowAirPlay        = 0x40,
    AVAudioSessionCategoryOptionOverrideMutedMicrophoneInterruption  = 0x80,
};
0x01 -> 0x00000001 -> 0b00000001
0x02 -> 0x00000002 -> 0b00000010
0x04 -> 0x00000004 -> 0b00000100
0x08 -> 0x00000008 -> 0b00001000
0x11 -> 0x00000011 -> 0b00010001
0x20 -> 0x00000020 -> 0b00100000
0x40 -> 0x00000040 -> 0b01000000

注:0x11 & 0x01 = 1 说明 0x11的情况包含0x01,从英文命名上也可以看出
  • 拼接多个值:用|运算
AVAudioSessionCategoryOptions options = AVAudioSessionCategoryOptionAllowBluetooth | AVAudioSessionCategoryOptionDefaultToSpeaker | ... | ...;
  • 取值: 用&运算
if (options & AVAudioSessionCategoryOptionAllowBluetooth) {
    // AVAudioSessionCategoryOptionAllowBluetooth
}
if (options & AVAudioSessionCategoryOptionDefaultToSpeaker) {
    // AVAudioSessionCategoryOptionDefaultToSpeaker
}

相关文章

网友评论

      本文标题:iOS 方法参数‘按位或’的原理

      本文链接:https://www.haomeiwen.com/subject/flnhwltx.html