设计一个自定义小型对象,利用 Tagged Pointer 思想节省 50% 内存,给出位域设计

解读

国内一线/二线 iOS 面试中,Tagged Pointer 属于“必问”底层优化点。
题目要求“自定义小型对象”,意味着不能直接用 NSNumber/NSDate 等系统实现,而要自己构造一个“伪对象”,让外部调用者仍用 id 接收、用 [] 语法发消息,同时内存占用比常规 64 位指针(8 Byte)减半(≤4 Byte)。
核心思路:

  1. 利用 64 位指针地址对齐 16 Byte 的特性,最低 4 bit 恒为 0,可借来做 tag。
  2. 将“对象”状态直接编码到这 4 bit + 更高位,不额外分配堆内存。
  3. 对外暴露的“类”需要重写 alloc/retain/release 等全套 NSObject 方法,防止消息转发到 NSObject 时崩溃。
  4. 位域设计要同时满足:
    • 节省 50% 内存(≤4 Byte)
    • 支持常见小对象语义(如整数、布尔、短字符串、RGB 色值等)
    • 支持运行时快速解码,不损失性能

知识点

  • Tagged Pointer 原理:arm64/x86_64 中,若指针最低有效位(LSB)(或 arm64 的 _OBJC_TAG_MASK 0x7)非 0,则运行时将其当“立即数”对象,不 deref。
  • objc-internal 结构:_objc_taggedPointerObfuscator、_objc_makeTaggedPointer、_objc_getTaggedPointerValue。
  • 位域(Bit-field)在 C/Obj-C 中的布局规则:编译器按从低到高或高到低分配,需用 union 明确对齐。
  • 自定义 tagged 类需实现:
    • +allocWithZone: 返回 tagged 值
    • -retain/-release/-dealloc 空实现
    • -isEqual:、-hash、-description 等覆盖
  • 内存对齐:16 Byte 对齐保证最低 4 bit 为 0;arm64 上系统保留 3 bit tag,用户可再用 1 bit 扩展。
  • 国内面试常追问“为什么能省内存”“多线程安全吗”“与 ARC 如何协作”“如何调试 tagged 对象崩溃”。

答案

以下给出一个可直接通过 clang 编译的 Demo,实现一个“3 通道 4-bit 颜色 + 1 通道 2-bit 透明度”的小对象,总 payload 14 bit,加上 2 bit tag,共 16 bit,远小于 8 Byte 指针,满足“节省 50% 内存”要求。

#import <objc/runtime.h>

// 1. 位域设计
typedef union {
    uintptr_t raw;
    struct {
        uintptr_t r : 4;   // Red   0-15
        uintptr_t g : 4;   // Green 0-15
        uintptr_t b : 4;   // Blue  0-15
        uintptr_t a : 2;   // Alpha 0-3
        uintptr_t tag : 2; // 用户 tag,固定 0b01
    } bits;
} TaggedColor;

// 2. 自定义 tagged 类
@interface TaggedColorObj : NSObject
+ (instancetype)colorWithR:(uint8_t)r g:(uint8_t)g b:(uint8_t)b a:(uint8_t)a;
@property (nonatomic, readonly) uint8_t red;
@property (nonatomic, readonly) uint8_t green;
@property (nonatomic, readonly) uint8_t blue;
@property (nonatomic, readonly) uint8_t alpha;
@end

@implementation TaggedColorObj

// 禁止堆分配
+ (instancetype)allocWithZone:(struct _NSZone *)zone {
    // 外部应使用工厂方法,这里返回 nil 防止误用
    return nil;
}

// 工厂方法:构造 tagged 值
+ (instancetype)colorWithR:(uint8_t)r g:(uint8_t)g b:(uint8_t)b a:(uint8_t)a {
    TaggedColor tc = {0};
    tc.bits.tag = 0b01;                // 用户自定义 tag
    tc.bits.r = r & 0xF;
    tc.bits.g = g & 0xF;
    tc.bits.b = b & 0xF;
    tc.bits.a = a & 0x3;
    // 将 16 位 payload 放入高 48 位,最低 4 位留 0b0100,满足 tagged mask
    uintptr_t value = (tc.raw << 4) | 0b0100;
    return (__bridge instancetype)(void *)value;
}

// 解码
- (TaggedColor)decode {
    // 去掉最低 4 位 tag
    uintptr_t raw = (uintptr_t)self >> 4;
    TaggedColor tc = { .raw = raw };
    return tc;
}

- (uint8_t)red   { return (uint8_t)self.decode.bits.r; }
- (uint8_t)green { return (uint8_t)self.decode.bits.g; }
- (uint8_t)blue  { return (uint8_t)self.decode.bits.b; }
- (uint8_t)alpha { return (uint8_t)self.decode.bits.a; }

// 内存管理空实现
- (id)retain { return self; }
- (oneway void)release {}
- (id)autorelease { return self; }
- (NSUInteger)retainCount { return NSUIntegerMax; }

// 调试
- (NSString *)description {
    return [NSString stringWithFormat:@"<%@ = %p, r=%tu g=%tu b=%tu a=%tu>",
            NSStringFromClass([self class]), self,
            self.red, self.green, self.blue, self.alpha];
}
@end

使用示例:

id color = [TaggedColorObj colorWithR:15 g:0 b:8 a:3];
NSLog(@"%@", color);  // 输出 TaggedColorObj 地址,实际为 tagged 值

内存对比:
常规 NSObject 派生对象 = 16 Byte isa 指针 + 可能的 ivar 对齐 ≈ 16~32 Byte;
TaggedColorObj 仅占用 8 Byte 指针宽度,其中有效数据 16 bit,未额外分配堆内存,节省 ≥50%。

拓展思考

  1. 系统 Tagged Pointer 与用户自定义冲突:
    若最低 4 bit 与系统 tag 重叠,需向运行时注册新的 tag index(objc_tag_index_t),使用 _objc_makeTaggedPointer(idx, payload) 生成,否则可能在 iOS 17 上触发异常。
  2. 多线程安全:
    Tagged Pointer 本质是值类型,无共享堆数据,读写天然原子,但自定义逻辑若引入全局缓存表,需要锁保护。
  3. ARC 适配:
    重写 retain/release 后,ARC 不会插入额外代码;若忘记覆盖,会在运行时插入 objc_retain,导致崩溃。
  4. 调试技巧:
    在 lldb 使用 po (id)0x0000000000000123 可直接打印 tagged 值;若出现 EXC_BAD_ACCESS,先检查最低位 tag 是否合法。
  5. 国内面试追问方向:
    • “为什么 arm64 用 3 bit 做 tag,x86_64 用 4 bit?”
    • “Tagged Pointer 与 Swift 的值类型优化有何异同?”
    • “若 payload 超过 60 bit,如何降级到堆对象?”
      准备时务必结合源码(objc4-818.2)与真机调试,展示“能讲清、能下断点、能改源码”的硬核能力。