面试01-isa
1:
union isa_t {
isa_t() { }
isa_t(uintptr_t value) : bits(value) { }
uintptr_t bits;
Class cls;
#if defined(ISA_BITFIELD)
struct {
ISA_BITFIELD; // 具体位域定义在 isa.h 中,按架构区分
};
#endif
};
arm64 架构下的位域布局
在 arm64(真机)上,ISA_BITFIELD 的定义如下(来自 objc4 源码 isa.h):
在 64 位架构下,isa 不再是单纯的指针,而是一个 union isa_t(非指针 isa / nonpointer isa),除了保存类地址(shiftcls 位段),还用位域压缩存储了引用计数、是否有弱引用、是否有关联对象、是否正在析构等信息,节省内存并提升访问效率。
uintptr_t nonpointer : 1; // bit 0 uintptr_t has_assoc : 1; // bit 1 uintptr_t has_cxx_dtor : 1; // bit 2 uintptr_t shiftcls : 33; // bits 3~35 uintptr_t magic : 6; // bits 36~41 uintptr_t weakly_referenced : 1; // bit 42 uintptr_t deallocating : 1; // bit 43 uintptr_t has_sidetable_rc : 1; // bit 44 uintptr_t extra_rc : 19; // bits 45~63
每个字段的精确含义
| 字段 | 位宽(arm64 / x86_64) | 含义 |
|---|---|---|
nonpointer |
1 / 1 | 0 表示 isa 是纯类指针;1 表示启用了优化 isa,后面的位域才有意义 |
has_assoc |
1 / 1 | 是否设置过关联对象。为 0 时对象释放可以跳过关联对象的清理逻辑,更快释放 |
has_cxx_dtor |
1 / 1 | 是否有 C++ 析构函数(.cxx_destruct)。为 0时释放可以跳过 C++ 析构调用 |
shiftcls |
33 / 44 | 存储 Class / Meta-Class 对象的地址。因为指针按 8 字节对齐,低 3 位总是 0,所以实际存储的是 cls >> 3 的值 |
magic |
6 / 6 | 调试器用于区分“有效对象”和“未初始化内存”的魔数 |
weakly_referenced |
1 / 1 | 是否被 weak 指针指向过。为 0 时释放可以跳过 weak 表清理,更快释放 |
deallocating |
1 / 1 | 对象是否正在执行 dealloc 流程 |
has_sidetable_rc |
1 / 1 | 引用计数是否已溢出,需要借助 SideTable 存储。为 1 时 extra_rc 只保存一部分计数 |
extra_rc |
19 / 8 | 对象的额外引用计数,实际引用计数 = extra_rc + 1。例如 extra_rc 为 5,引用计数就是 6 |
1. 属性关键字:不是背区别,是看 setter/getter 生成
atomic、noatomic、assign、copy、mutablecopy、weak
| 关键字 | 底层语义 | 深挖点 |
|---|---|---|
assign |
直接赋值,不改变引用计数 | 对象用会悬垂;基本类型默认 |
weak |
ARC 下不持有,对象释放自动置 nil | 依赖 SideTable/weak_table |
unsafe_unretained |
不持有,不自动置 nil | 等价 MRC assign,性能好但危险 |
strong / retain |
持有,旧值 release,新值 retain | ARC 下 strong,MRC 下 retain |
copy |
setter 调 copyWithZone: |
对 NSMutableString/NSMutableArray防御 |
atomic |
getter/setter 内部加锁。默认 | 只保证单次读写原子,不保证复合操作 |
nonatomic |
不加锁 | 默认不是,性能高,UI 常用 |
readwrite |
生成 getter/setter | 可在 class extension 重写 readonly |
readonly |
只生成 getter | 外部不能 set |
class |
类属性 | 不自动 synthesize,需手写实现 |
getter= / setter= |
自定义访问器名 | 影响 KVC/KVO 查找 |
nullable/nonnull/null_resettable |
空值语义 | Swift 混编重要 |
instancetype |
返回当前类实例 |
编译期类型检查,优于 |

引用
https://cloud.tencent.cn/developer/inventory/8489
浙公网安备 33010602011771号