使用枚举来定义内容和顺序
代码如下:
定义:
//内容
typedef NS_OPTIONS(NSUInteger, ContentType) {
A1 = 1,
A2 = 2,
A3 = 3,
A4 = 4,
A5 = 5,
A6 = 6,
A7 = 7,
A8 = 8
};
//顺序
typedef NS_OPTIONS(NSUInteger, PositionType) {
P1 = 0xF0000000,
P2 = 0x0F000000,
P3 = 0x00F00000,
P4 = 0x000F0000,
P5 = 0x0000F000,
P6 = 0x00000F00,
P7 = 0x000000F0,
P8 = 0x0000000F
};
使用:
NSUInteger testNumber1 = (A1 << 28) | (A4 << 24) | (A2 << 20) | (A7 << 16) | (A3 << 12) | (A8 << 8) | (A6 << 4) | (A5 << 0);
解析
NSString *positionNumber1 = [self valueOnPosition:testNumber1 position:P1];
NSString *positionNumber2 = [self valueOnPosition:testNumber1 position:P2];
NSString *positionNumber3 = [self valueOnPosition:testNumber1 position:P3];
NSString *positionNumber4 = [self valueOnPosition:testNumber1 position:P4];
NSString *positionNumber5 = [self valueOnPosition:testNumber1 position:P5];
NSString *positionNumber6 = [self valueOnPosition:testNumber1 position:P6];
NSString *positionNumber7 = [self valueOnPosition:testNumber1 position:P7];
NSString *positionNumber8 = [self valueOnPosition:testNumber1 position:P8];
NSLog(@"positionNumber1 : %@, \npositionNumber2 : %@, \npositionNumber3 : %@, \npositionNumber4 : %@, \npositionNumber5 : %@, \npositionNumber6 : %@, \npositionNumber7 : %@, \npositionNumber8 : %@", positionNumber1, positionNumber2, positionNumber3, positionNumber4, positionNumber5, positionNumber6, positionNumber7, positionNumber8);
- (NSString *)valueOnPosition:(NSUInteger)number position:(NSUInteger)position{
NSUInteger contentNumber = position & number;
switch (position) {
case P1:
contentNumber = contentNumber >> 28;
break;
case P2:
contentNumber = contentNumber >> 24;
break;
case P3:
contentNumber = contentNumber >> 20;
break;
case P4:
contentNumber = contentNumber >> 16;
break;
case P5:
contentNumber = contentNumber >> 12;
break;
case P6:
contentNumber = contentNumber >> 8;
break;
case P7:
contentNumber = contentNumber >> 4;
break;
case P8:
contentNumber = contentNumber >> 0;
break;
default:
break;
}
return [self getValue:contentNumber];
}
- (NSString *)getValue:(NSUInteger)number{
if (number == A1) {
return @"A1";
}else if (number == A2){
return @"A2";
}else if (number == A3){
return @"A3";
}else if (number == A4){
return @"A4";
}else if (number == A5){
return @"A5";
}else if (number == A6){
return @"A6";
}else if (number == A7){
return @"A7";
}else if (number == A8){
return @"A8";
}
return @"unknown";
}
网友评论