使用共用体做内存优化

案例

XSYPerson.h文件

#import 

NS_ASSUME_NONNULL_BEGIN

@interface XSYPerson : NSObject

- (void)setAge:(BOOL)age;
- (void)setWeight:(BOOL)weight;
- (void)setHeight:(BOOL)height;

- (BOOL)age;
- (BOOL)weight;
- (BOOL)height;

@end

NS_ASSUME_NONNULL_END

XSYPerson.m 文件

#import "XSYPerson.h"

#define AgeMask    (1)
#define WeightMask (1 << 1)
#define HeightMask (1 << 2)

@implementation XSYPerson {
    union {
        char bits; // 用来存储共用体的数据
        struct { // 解释作用
            BOOL age : 1;
            BOOL weight : 1;
            BOOL height : 1;
        };
    } AgeWightHeight;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        
    }
    return self;
}

- (void)setAge:(BOOL)age {
    if (age) {
        AgeWightHeight.bits |= age;
    }else {
        AgeWightHeight.bits &= ~AgeMask;
    }
}

- (BOOL)age {
    return !!(AgeWightHeight.bits & AgeMask);
}

- (void)setWeight:(BOOL)weight {
    if (weight) {
        AgeWightHeight.bits |= WeightMask;
    }else {
        AgeWightHeight.bits &= ~WeightMask;
    }
}

- (BOOL)weight {
    return !!(AgeWightHeight.bits & WeightMask);
}

- (void)setHeight:(BOOL)height {
    if (height) {
        AgeWightHeight.bits |= HeightMask;
    }else {
        AgeWightHeight.bits &= ~HeightMask;
    }
}

- (BOOL)height {
    return !!(AgeWightHeight.bits & HeightMask);
}

@end

使用

XSYPerson *person = [[XSYPerson alloc] init];
person.age = YES;
person.weight = NO;
person.height = YES;
NSLog(@"age %d, weight %d, heigt %d",person.age, person.weight, person.height);

打印:
age 1, weight 0, heigt 1

你可能感兴趣的:(使用共用体做内存优化)