Skip to content

Latest commit

 

History

History
61 lines (51 loc) · 2.61 KB

移位枚举.md

File metadata and controls

61 lines (51 loc) · 2.61 KB

移位枚举

我们在iOS代码中,经常会看到这种枚举:

typedef NS_OPTIONS(NSUInteger, UIRemoteNotificationType) {
    UIRemoteNotificationTypeNone    = 0,        //0000
    UIRemoteNotificationTypeBadge   = 1 << 0,   //0001
    UIRemoteNotificationTypeSound   = 1 << 1,   //0010
    UIRemoteNotificationTypeAlert   = 1 << 2,   //0100
    UIRemoteNotificationTypeNewsstandContentAvailability = 1 << 3,
}

这种枚举,其实就是位移枚举.[<<]就是位移操作,将1右移。这块可以去google:位移

那么我们使用下面的方法,又是什么意思呢?

[[[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIUserNotificationTypeAlert |UIUserNotificationTypeBadge | UIUserNotificationTypeSound )]]
  1. 其实就是说明,这个通知有Alert+Badge+Sound

  2. 那么为什么可以这样表示呢

    1. 首先,我们需要了解位操作符[|]:或
    2. 它的意思就是将0/1做对比,如果有一方是1,则就是1.其他情况就都是0
    3. 那么我们上面的几个[|]就可以表示为:[0001|0010|0100]位运算后,其实就是[0111]
    4. 当调用[[[UIApplication sharedApplication] registerForRemoteNotificationTypes:notificationType]]这个方法的时候,这个方法内部,就会使用相当于下面这种判断方式,然后将三种Type都注册上:
    UIUserNotificationType notificationType = [UIUserNotificationTypeAlert |UIUserNotificationTypeBadge | UIUserNotificationTypeSound]
    
    if(notificationType & UIUserNotificationTypeAlert){
    	//...
    }
    if(notificationType & UIUserNotificationTypeBadge){
    	//...
    }
    if(notificationType & UIUserNotificationTypeSound){
    	//...
    }
    
  3. [notificationType & UIUserNotificationTypeSound]又是什么意思呢?[&]:并操作符,将0/1进行比较,必须两方都是1,才是1.

  4. 那么[notificationType & UIUserNotificationTypeSound]其实就是[0111&0100]=[0100],符合ture的条件,进入语句

  5. 这就表示,这个是支持notificationTypeSoundType的

  6. 假如,我们[notificationType=UIUserNotificationTypeAlert |UIUserNotificationTypeBadge],那么我们的判断条件[notificationType & UIUserNotificationTypeSound]其实就是[0011&0100]=[0000],这样,就不会进入判断条件了

  7. 举个例子:

typedef NS_OPTIONS(NSInteger, Num) {
    Num_1 = 1<<0,   //0001
    Num_2 = 1<<1,	   //0010
    Num_4 = 1<<2    //0100
};
//如果是Num_1 或者Num_4 都可以进入条件语句
Num n = Num_1;  //0001
if (n & (Num_1|Num_4)) {     //0001 & (0001|0100) = 0001 & 0101 = 0001 符合条件,是true,进入语句
   NSLog(@"111");
}