需求:设计一个对象DXPerson
,三个BOOL类型属性(tall,rich,handsom),只占用一个字节内存
使用共用体union实现,本质跟char _tallRichHandsome
实现一个原理
共用体union
,共同占用一个内存
union {
int year;
int month;
int day;
}date;
date.year = 2011;
date.month = 10;
NSLog(@"%d",date.year); // 10
date.year
会被date.month
覆盖,因此打印是10
.h文件声明
@interface DXPerson : NSObject
- (BOOL)isTall;
- (BOOL)isRich;
- (BOOL)isHandsome;
- (void)setTall:(BOOL)tall;
- (void)setRich:(BOOL)rich;
- (void)setHandsome:(BOOL)handsome;
@end
.m文件实现
@interface DXPerson(){
// 共用体,共同占用一个内存
union {
// bit的复数,一个字节 == 8bit
// bits用来存放所有数据
char bits;
// 结构体可以删除,仅仅是为了增强可读性
struct{
// 位域 : 1表示只占用一位,如果:2,表示占用两位,默认第一个变量占用最后一位
char tall : 1; // 最后一位
char rich : 1;// 倒数第二位
char handsome : 1;// 倒数第三位
};
}_tallRichHandsome;
}
@end
#define DXTallMask (1<<0)
#define DXRichMask (1<<1)
#define DXHandsomeMask (1<<2)
@implementation DXPerson
- (instancetype)init{
self = [super init];
if (self) {
// 初始值设置 tall == 1 rich == 0 handsome == 1
_tallRichHandsome.bits = 0b00000101;
}
return self;
}
- (BOOL)isTall{
return !!(_tallRichHandsome.bits & DXTallMask);
}
- (BOOL)isRich{
return !!(_tallRichHandsome.bits & DXRichMask);
}
- (BOOL)isHandsome{
return !!(_tallRichHandsome.bits & DXHandsomeMask);
}
- (void)setTall:(BOOL)tall{
if (tall) {
_tallRichHandsome.bits |= DXTallMask;
} else {
_tallRichHandsome.bits &= ~DXTallMask;
}
}
- (void)setRich:(BOOL)rich{
if (rich) {
_tallRichHandsome.bits |= DXRichMask;
} else {
_tallRichHandsome.bits &= ~DXRichMask;
}
}
- (void)setHandsome:(BOOL)handsome{
if (handsome) {
_tallRichHandsome.bits |= DXHandsomeMask;
} else {
_tallRichHandsome.bits &= ~DXHandsomeMask;
}
}
@end
打印
DXPerson *person = [[DXPerson alloc] init];
[person setTall:NO];
[person setRich:YES];
[person setHandsome:NO];
// tall = 0, rich = 1, handsome = 0
NSLog(@"tall = %d, rich = %d, handsome = %d", person.isTall,person.isRich,person.isHandsome);