知识点总结17:位运算符

枚举值的某个规律

  • 凡是使用了1 << n格式的枚举值, 都可以使用|进行组合使用
UIControlEventEditingDidBegin                                   = 1 << 16,
UIControlEventEditingChanged                                    = 1 << 17,
UIControlEventEditingDidEnd                                     = 1 << 18,
UIControlEventEditingDidEndOnExit                               = 1 << 19,

[textField addTarget:self action:@selector(test) forControlEvents:UIControlEventEditingDidBegin | UIControlEventEditingChanged];

用位运算表示的方法才能组合使用,具体原因如下:

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    /**** 只有位运算的方法选项才能组合在一起用 ****/
    int a = 1 << 0; // 1       1左移0位 = 2的0次方
    int b = 1 << 1; // 2       1左移1位 = 2的1次方
    int c = 1 << 2; // 4       1左移2位 = 2的2次方
    int d = 1 << 3; // 8       1左移3位 = 2的3次方
    NSLog(@"方法的所有可能数: %d-%d-%d-%d", a, b, c, d);
    
    // 检验包含了多少可能
    // 检验数是value,它是所有可能的或运算,方法内部通过与运算来检验
    /* 1.检验数的获得
     0001
     0010
     0100
     ---------
     0111 value(或运算计算出value) 
     a | b | c = value = 0111
     */
    [self functionWithValue:a | d | b testValueOne:a testValueTwo:b testValueThree:c testValueFour:d];
    
    /* 2.内部检查机制
        0111&    value&
        0001     a
     ----------  ---------
        0001     包含有a
     
     
        0111&    value&
        1000     d
     ----------  ---------
        0000     不包含有d
     */
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (void)functionWithValue: (int)value testValueOne: (int)testValueOne testValueTwo: (int)testValueTwo testValueThree: (int)testValueThree testValueFour: (int)testValueFour{
    // a
    if (value & testValueOne) {
        NSLog(@"value包含了a---%d", testValueOne);
    }
    // b
    if (value & testValueTwo) {
        NSLog(@"value包含了b---%d", testValueTwo);
    }
    // c
    if (value & testValueThree) {
        NSLog(@"value包含了c---%d", testValueThree);
    }
    // d
    if (value & testValueFour) {
        NSLog(@"value包含了d---%d", testValueFour);
    }
    
}

@end

你可能感兴趣的:(知识点总结17:位运算符)