联合体与结构体
结构体
结构体是指把不同的数据组合成一个整体,其变量是共存的,变量不管是否使用,都会分配内存。
缺点:所有属性都分配内存,比较浪费内存,假设有4个int成员,一共分配了16字节的内存,但是在使用时,你只使用了4字节,剩余的12字节就是属于内存的浪费
优点:存储容量较大,包容性强,且成员之间不会相互影响
联合体
联合体也是由不同的数据类型组成,但其变量是互斥的,所有的成员共占一段内存。而且共用体采用了内存覆盖技术,同一时刻只能保存一个成员的值,如果对新的成员赋值,就会将原来成员的值覆盖
缺点:包容性弱
优点:所有成员共用一段内存,使内存的使用更为精细灵活,同时也节省了内存空间
两者的区别
结构体的各个成员会占用不同的内存,互相之间没有影响
共用体的所有成员占用同一段内存,修改一个成员会影响其余所有成员
结构体内存 大于等于 所有成员占用的内存总和(成员之间可能会有缝隙)
共用体占用的内存等于最大的成员占用的内存
Clang编译器
-
clang是由 Apple 主导编写,基于LLVM的C/C++/OC的编译器 - 主要是用于
底层编译,将一些OC文件输出成c++文件,其目的是为了更好的观察底层的一些结构及实现的逻辑,方便理解底层原理。例如main.m 输出成main.cpp,
终端 clang -- oc转c++文件的方法
//1、将 main.m 编译成 main.cpp
clang -rewrite-objc main.m -o main.cpp
//2、将 ViewController.m 编译成 ViewController.cpp
clang -rewrite-objc -fobjc-arc -fobjc-runtime=ios-13.0.0 -isysroot / /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.7.sdk ViewController.m
//以下两种方式是通过指定架构模式的命令行,使用xcode工具 xcrun
//3、模拟器文件编译
- xcrun -sdk iphonesimulator clang -arch arm64 -rewrite-objc main.m -o main-arm64.cpp
//4、真机文件编译
- xcrun -sdk iphoneos clang -arch arm64 -rewrite-objc main.m -o main- arm64.cpp
OC对象的本质
- 首先我们在
main.m中自定义一个YPPerson类
@interface YPPerson : NSObject
@property (nonatomic, copy) NSString *name;
@end
@implementation LGPerson
@end
打开终端
cd到当前main.m目录,输入clang -rewrite-objc main.m -o main.cpp回车,在当前目录下会生成一个main.cpp文件-
打开
main.cpp文件,搜索YPPerson就还会发现一个YPPerson_IMPL的结构体,所以我们确定OC对象的本质就是结构体
image.png-
YPPerson_IMPL中有个继承(伪继承)自NSObject的NSObject_IVARS,NSObject_IVARS等效于isa
-
// YPPerson
struct YPPerson_IMPL {
struct NSObject_IMPL NSObject_IVARS;
NSString *_name;
};
// NSObject底层编译
struct NSObject_IMPL {
Class isa;
};
// NSObject的定义(在objc源码中)
@interface NSObject <NSObject> {
//#pragma clang diagnostic push
//#pragma clang diagnostic ignored "-Wobjc-interface-ivars"
Class isa OBJC_ISA_AVAILABILITY;
//#pragma clang diagnostic pop
}
在main.cpp文件我们还发现了属性name的set、get方法,通过依赖于runtime中的objc_setProperty方法
我们可以在objc的源码中搜索objc_setProperty找到对应的实现
- 在
reallySetProperty方法中可以发现实现的原理是新值retain和旧值release
//objc_setProperty
void objc_setProperty(id self, SEL _cmd, ptrdiff_t offset, id newValue, BOOL atomic, signed char shouldCopy)
{
bool copy = (shouldCopy && shouldCopy != MUTABLE_COPY);
bool mutableCopy = (shouldCopy == MUTABLE_COPY);
reallySetProperty(self, _cmd, newValue, offset, atomic, copy, mutableCopy);
}
//reallySetProperty
static inline void reallySetProperty(id self, SEL _cmd, id newValue, ptrdiff_t offset, bool atomic, bool copy, bool mutableCopy)
{
if (offset == 0) {
object_setClass(self, newValue);
return;
}
id oldValue;
id *slot = (id*) ((char*)self + offset);
if (copy) {
newValue = [newValue copyWithZone:nil];
} else if (mutableCopy) {
newValue = [newValue mutableCopyWithZone:nil];
} else {
if (*slot == newValue) return;
newValue = objc_retain(newValue);
}
if (!atomic) {
oldValue = *slot;
*slot = newValue;
} else {
spinlock_t& slotlock = PropertyLocks[slot];
slotlock.lock();
oldValue = *slot;
*slot = newValue;
slotlock.unlock();
}
objc_release(oldValue);
}
isa和类的绑定
- 在OC源码探索02:alloc、init和new的区别中我们发现
alloc的核心方法initInstanceIsa,作用是将cls和isa绑定, 但是在初始化isa的时候是isa_t类型的 ,所以在返回的时候系统对isa做了Class的类型强转
inline Class
objc_object::ISA()
{
ASSERT(!isTaggedPointer());
#if SUPPORT_INDEXED_ISA
if (isa.nonpointer) {
uintptr_t slot = isa.indexcls;
return classForIndex((unsigned)slot);
}
return (Class)isa.bits;
#else
return (Class)(isa.bits & ISA_MASK);
#endif
}
isa_t
union isa_t { //联合体
isa_t() { }
isa_t(uintptr_t value) : bits(value) { }
//提供了cls 和 bits ,两者是互斥关系
Class cls;
uintptr_t bits;
#if defined(ISA_BITFIELD)
struct {
ISA_BITFIELD; // defined in isa.h
};
#endif
};
我们从isa_t的源码中可发现是由联合体定义的,isa指针中通过char + 位域(即二进制中每一位均可表示不同的信息)的原理实现。通常来说,isa指针占用的内存大小是8字节,即64位
从
- 从
isa_t的源码中有cls和bits两个成员,因为isa_t是联合体,所以isa指针在初始化时有两种初始化方法- 通过
cls初始化,bits无默认值 - 通过
bits初始化,cls有默认值
- 通过
-
isa_t中还定义了一个位域(ISA_BITFIELD)用于存储类信息及其他信息,ISA_BITFIELD有两个版本,__arm64__(对应ios 移动端) 和__x86_64__(对应macOS)-
nonpointer有两个值,表示自定义的类等,占1位-
0:纯isa指针 -
1:不只是类对象地址,isa中包含了类信息、对象的引用计数等
-
-
has_assoc表示关联对象标志位,占1位-
0:没有关联对象 -
1:存在关联对象
-
-
has_cxx_dtor表示该对象是否有C++/OC的析构器(类似于dealloc),占1位- 如果有析构函数,则需要
做析构逻辑 - 如果没有,则可以
更快的释放对象
- 如果有析构函数,则需要
shiftclx表示存储类的指针的值(类的地址), 即类信息arm64中占33位,开启指针优化的情况下,在arm64架构中有33位用来存储类指针x86_64中占44位magic用于调试器判断当前对象是真的对象还是没有初始化的空间,占6位weakly_refrenced是指对象是否被指向或者曾经指向一个ARC的弱变量,没有弱引用的对象可以更快释放deallocating标志对象是是否正在释放内存has_sidetable_rc表示 当对象引用计数大于10时,则需要借用该变量存储进位extra_rc(额外的引用计数)表示该对象的引用计数值,实际上是引用计数值减1,如果对象的引用计数为10,那么extra_rc为9
-
# if __arm64__ //iOS
# define ISA_MASK 0x0000000ffffffff8ULL
# define ISA_MAGIC_MASK 0x000003f000000001ULL
# define ISA_MAGIC_VALUE 0x000001a000000001ULL
# define ISA_BITFIELD
uintptr_t nonpointer : 1; // 是否对isa指针开启指针优化
uintptr_t has_assoc : 1; // 是否有关联对象
uintptr_t has_cxx_dtor : 1; // 是否有C++实现
uintptr_t shiftcls : 33; /*MACH_VM_MAX_ADDRESS 0x1000000000*///存储类信息
uintptr_t magic : 6; // 调试器判断对象是真对象还是为初始化空间
uintptr_t weakly_referenced : 1; // 对象是否被指向或者曾经指向一个ARC的弱引用
uintptr_t deallocating : 1; // 标志对象是否正在释放内存
uintptr_t has_sidetable_rc : 1; // 是否有外挂的散列表
uintptr_t extra_rc : 19 // 额外的引用计数
# define RC_ONE (1ULL<<45)
# define RC_HALF (1ULL<<18)
# elif __x86_64__
# define ISA_MASK 0x00007ffffffffff8ULL
# define ISA_MAGIC_MASK 0x001f800000000001ULL
# define ISA_MAGIC_VALUE 0x001d800000000001ULL
# define ISA_BITFIELD \
uintptr_t nonpointer : 1; \
uintptr_t has_assoc : 1; \
uintptr_t has_cxx_dtor : 1; \
uintptr_t shiftcls : 44; /*MACH_VM_MAX_ADDRESS 0x7fffffe00000*/ \
uintptr_t magic : 6; \
uintptr_t weakly_referenced : 1; \
uintptr_t deallocating : 1; \
uintptr_t has_sidetable_rc : 1; \
uintptr_t extra_rc : 8
# define RC_ONE (1ULL<<56)
# define RC_HALF (1ULL<<7)


位运算验证
定义一个继承自 NSObject 的类YPPerson,不添加任何属性与方法
因为YPPerson继承自NSObject,默认有一个 isa,所以 0x021d8001000020f1 就是 isa_t 结构。所以我们将0x021d8001000020f1 右移3位,左移31位,再右移28位,最终结果显示是拿到了YPPerson类信息,刚好对应上面所说的shiftcls的数据信息

Dealloc
我们可以在objc的源码中可以搜索dealloc方法,跳转到_objc_rootDealloc -->rootDealloc,在rootDealloc方法中先判断isa.nonpointer、isa.weakly_referenced、isa.has_assoc 、isa.has_cxx_dtor、isa.has_sidetable_rc这五种情况,如果含有任意一种就会调用object_dispose方法,反之如果五种情况都么有,就直接调用C函授free()
inline void
objc_object::rootDealloc()
{
if (isTaggedPointer()) return; // fixme necessary?
if (fastpath(isa.nonpointer &&
!isa.weakly_referenced &&
!isa.has_assoc &&
!isa.has_cxx_dtor &&
!isa.has_sidetable_rc))
{
assert(!sidetable_present());
free(this);
}
else {
object_dispose((id)this);
}
}
再点击到object_dispose -->object_dispose就可以发现obj的是否流程
首先判断hasCxxDtor(C++相关内容),再判断hasAssociatedObjects(管理对象),来进行对应释放,然后在调用clearDeallocating方法
void *objc_destructInstance(id obj)
{
if (obj) {
// Read all of the flags at once for performance.
bool cxx = obj->hasCxxDtor();//c++相关
bool assoc = obj->hasAssociatedObjects();//关联对象
// This order is important.
if (cxx) object_cxxDestruct(obj);//c++相关
if (assoc) _object_remove_assocations(obj);//关联对象
obj->clearDeallocating();
}
return obj;
}
先执行sidetable_clearDeallocating方法,在执行clearDeallocating_slow(释放散列表)方法
inline void
objc_object::clearDeallocating()
{
if (slowpath(!isa.nonpointer)) {
// Slow path for raw pointer isa.
sidetable_clearDeallocating();
}
else if (slowpath(isa.weakly_referenced || isa.has_sidetable_rc)) {
// Slow path for non-pointer isa with weak refs and/or side table data.
clearDeallocating_slow();
}
assert(!sidetable_present());
}
执行weak_clear_no_lock(弱引用指针表)和refcnts.erase(引用计数表),到此为止,Dealloc方法执行完毕
objc_object::clearDeallocating_slow()
{
ASSERT(isa.nonpointer && (isa.weakly_referenced || isa.has_sidetable_rc));
SideTable& table = SideTables()[this];
table.lock();
if (isa.weakly_referenced) {
weak_clear_no_lock(&table.weak_table, (id)this);
}
if (isa.has_sidetable_rc) {
table.refcnts.erase(this);
}
table.unlock();
}
