共用体的所有成员占用同一段内存,修改一个成员会影响其余所有成员。
共用体占用的内存等于最长的成员占用的内存
常用创建方式1
union Data{
int n;
char ch;
double f;
} a, b, c;
常用创建方式2
union Data{
int n;
char ch;
double f;
};
union data a, b, c;
定义一个Car
类,有向前,向后,向左,向右四个属性
#import <Foundation/Foundation.h>
@interface Car : NSObject
@property (nonatomic, assign) BOOL front;
@property (nonatomic, assign) BOOL back;
@property (nonatomic, assign) BOOL left;
@property (nonatomic, assign) BOOL right;
@end
#import "Car.h"
//(1 << 2) 数字1(0b00000001)向左移2位,后面补0 (0b00000100)
//0b00000001
#define DirectionFrontMask (1 << 0)
//0b00000010
#define LGDirectionBackMask (1 << 1)
//0b00000100
#define DirectionLeftMask (1 << 2)
//0b00001000
#define DirectionRightMask (1 << 3)
@interface Car(){
// 联合体
union Direction{
char bits;
// 位域
struct {
char front : 1;
char back : 1;
char left : 1;
char right : 1;
};
} _direction;
}
- (void)setFront:(BOOL)isFront {
if (isFront) {
//常用赋值
//赋值bits,把DirectionFrontMask位,赋值为true
_direction.bits |= DirectionFrontMask;
} else {
//赋值bits,把DirectionFrontMask位,赋值为false
_direction.bits &= ~DirectionFrontMask;
}
NSLog(@"%s",__func__);
}
- (BOOL)isFront{
return (BOOL)_direction.front;
// return !!_direction.front;
}
- (void)clearDirection{
_direction.front = 0;
//相当于
//_direction.front = 0;
//_direction.back = 0;
//_direction.left = 0;
//_direction.right = 0;
}
@end