需求:设计一个对象DXPerson,三个BOOL类型属性(tall,rich,handsom),只占用一个字节内存

.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(){
    
    // _tallRichHandsome是结构体类型
    struct{
        // 位域 : 1表示只占用一位,如果:2,表示占用两位,默认第一个变量占用最后一位
        char tall : 1; // 最后一位
        char rich : 1;// 倒数第二位
        char handsome : 1;// 倒数第三位
        
    }_tallRichHandsome;
}

@end

@implementation DXPerson

- (BOOL)isTall{
    return !!(_tallRichHandsome.tall);
}
- (BOOL)isRich{
    // 强制转换成BOOL类型,否则打印出来-1
    return !!(_tallRichHandsome.rich);
}

- (BOOL)isHandsome{
    return !!(_tallRichHandsome.handsome);
}

- (void)setTall:(BOOL)tall{
    _tallRichHandsome.tall = tall;
}
- (void)setRich:(BOOL)rich{
    _tallRichHandsome.rich = rich;
}
- (void)setHandsome:(BOOL)handsome{
    _tallRichHandsome.handsome = handsome;
}
@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);