iOS 全网最新objc4 可调式/编译源码
编译好的源码的下载地址
序言
在日常的iOS开发中,在创建对象时我们最常用的方法就是alloc、init、new,这几个方法是怎么开辟内存,创建对象的呢?
这里有一段代码,三个person变量,通过打印可以看出他们的指针和内存地址信息
LGPerson * person = [LGPerson alloc];
LGPerson * person1 = [person init];
LGPerson * person2 = [person init];
NSLog(@"person=%@ ** %p ** %p", person, person, &person);
NSLog(@"person1=%@ ** %p ** %p", person1, person1, &person1);
NSLog(@"person2=%@ ** %p ** %p", person2, person2, &person2);
通过打印输出
person=<LGPerson: 0x600002bc8040> ** 0x600002bc8040 ** 0x7ffee51f3c70
person1=<LGPerson: 0x600002bc8040> ** 0x600002bc8040 ** 0x7ffee51f3c68
erson2=<LGPerson: 0x600002bc8040> ** 0x600002bc8040 ** 0x7ffee51f3c60
通过打印信息可以看出,
person和person1以及person2的指针变量是不同的,但是却指向了同一个内存地址,所以这里可以基本看出内存的申请开辟是在alloc方法实现,init方法只是生成对象,并没有对内存空间做任何处理。
这里就是本文重点探究,那么alloc是怎么开辟内存的,以及init方法是怎么处理的。
底层探索的方法
这里需要用到苹果开源代码去研究,附上链接(源码汇总、OC:objc4-818.2)
方法1:符号断点
在需要调试的地方加上断点,运行代码跑到断点处,点击step into在终端输入si快捷进入汇编界面,这里看到alloc的底层方法是objc_alloc,然后给这个方法添加符号断点
objc_alloc的底层代码实现就在libobjc.A.dylib库中。
方法2:汇编
xcode的管理栏处,从debug中找到Debug Workflow然后开启Always Show Disassembly,进入到汇编界面,看到这里的callq代码调用解释是objc_alloc方法
方法3:已知方法 符号断点
直接按照方法1,对我们要调试的方法alloc下符号断点,也是找到对应的libobjc.A.dylib库
alloc源码探索
下面跟着源码看底层是怎么具体实现alloc方法流程的
1. alloc 方法调用的是_objc_rootAlloc
+ (id)alloc {
return _objc_rootAlloc(self);
}
2. 在_objc_rootAlloc中调用的是callAlloc方法
id _objc_rootAlloc(Class cls)
{
return callAlloc(cls, false/*checkNil*/, true/*allocWithZone*/);
}
3.在callAlloc方法中,我们找到方法_objc_rootAllocWithZone
// Class: 开辟内存的类, checkNil : false, allocWithZone: ture
static ALWAYS_INLINE id
callAlloc(Class cls, bool checkNil, bool allocWithZone=false)
{
#if __OBJC2__ // 是不是 objc2.0版本
if (slowpath(checkNil && !cls)) return nil;
//判断该类是否实现自自定义的 +allocWithZone,没有则进入if条件句
if (fastpath(!cls->ISA()->hasCustomAWZ())) {
return _objc_rootAllocWithZone(cls, nil);
}
#endif
// No shortcuts available.
if (allocWithZone) {
return ((id(*)(id, SEL, struct _NSZone *))objc_msgSend)(cls, @selector(allocWithZone:), nil);
}
return ((id(*)(id, SEL))objc_msgSend)(cls, @selector(alloc));
}
4._objc_rootAllocWithZone的方法实现调用_class_createInstanceFromZone
id
_objc_rootAllocWithZone(Class cls, malloc_zone_t *zone __unused)
{
// allocWithZone under __OBJC2__ ignores the zone parameter
return _class_createInstanceFromZone(cls, 0,nil,
OBJECT_CONSTRUCT_CALL_BADALLOC);
}
5._class_createInstanceFromZone方法是alloc整个流程的关键方法,在这里真正开辟了内存
static ALWAYS_INLINE id
_class_createInstanceFromZone(Class cls, size_t extraBytes, void *zone,
int construct_flags = OBJECT_CONSTRUCT_NONE,
bool cxxConstruct = true,
size_t *outAllocatedSize = nil)
{
ASSERT(cls->isRealized());
// Read class's info bits all at once for performance
bool hasCxxCtor = cxxConstruct && cls->hasCxxCtor();
bool hasCxxDtor = cls->hasCxxDtor();
bool fast = cls->canAllocNonpointer();
size_t size;
size = cls->instanceSize(extraBytes); // 关键1:计算类开辟内存的大小
if (outAllocatedSize) *outAllocatedSize = size;
id obj;
if (zone) {
obj = (id)malloc_zone_calloc((malloc_zone_t *)zone, 1, size);
} else {
obj = (id)calloc(1, size); // 关键2:申请内存
}
if (slowpath(!obj)) {
if (construct_flags & OBJECT_CONSTRUCT_CALL_BADALLOC) {
return _objc_callBadAllocHandler(cls);
}
return nil;
}
if (!zone && fast) {
obj->initInstanceIsa(cls, hasCxxDtor); // 关键3:关联当前类的isa
} else {
// Use raw pointer isa on the assumption that they might be
// doing something weird with the zone or RR.
obj->initIsa(cls);
}
if (fastpath(!hasCxxCtor)) {
return obj;
}
construct_flags |= OBJECT_CONSTRUCT_FREE_ONFAILURE;
return object_cxxConstructFromClass(obj, cls, construct_flags);
}
- 关键1:
instanceSize计算开辟内存的大小- 关键2:
calloc开辟内存,返回地址指针- 关键3:
initInstanceIsa初始化指针,和类关联起来
这里探索一下instanceSize方法,是怎么计算内存大小的
inline size_t instanceSize(size_t extraBytes) const {
// 快速计算内存大小
if (fastpath(cache.hasFastInstanceSize(extraBytes))) {
return cache.fastInstanceSize(extraBytes);
}
//计算类中所有变量需要的内存大小 extraBytes额外字节数一般是0
size_t size = alignedInstanceSize() + extraBytes;
// CF requires all objects be at least 16 bytes.
if (size < 16) size = 16;
return size;
}
fastInstanceSize方法
size_t fastInstanceSize(size_t extra) const
{
ASSERT(hasFastInstanceSize(extra));
if (__builtin_constant_p(extra) && extra == 0) {
return _flags & FAST_CACHE_ALLOC_MASK16;
} else {
size_t size = _flags & FAST_CACHE_ALLOC_MASK;
// remove the FAST_CACHE_ALLOC_DELTA16 that was added
// by setFastInstanceSize
return align16(size + extra - FAST_CACHE_ALLOC_DELTA16);
}
}
align1616字节对齐方法
static inline size_t align16(size_t x) {
return (x + size_t(15)) & ~size_t(15);
}
// May be unaligned depending on class's ivars.
uint32_t unalignedInstanceSize() const {
ASSERT(isRealized());
return data()->ro()->instanceSize;
}
// Class's ivar size rounded up to a pointer-size boundary.
uint32_t alignedInstanceSize() const {
return word_align(unalignedInstanceSize());
}
这里根据alignedInstanceSize方法看出,size实际上就是ivars也就是属性以8字节对齐的大小。
alloc流程总结
根据流程图总结一下alloc的流程
init方法
关于init的底层处理,可以看源码中的两段代码
// init 方法
- (id)init {
return _objc_rootInit(self);
}
id
_objc_rootInit(id obj)
{
// In practice, it will be hard to rely on this function.
// Many classes do not properly chain -init calls.
return obj;
}
init方法返回的是对象本身,类似工厂模式,init方法的意义是可以扩展更多的初始化方法。
new方法
+ (id)new {
return [callAlloc(self, false/*checkNil*/) init];
}
new方法的底层实现,其实就是调用alloc流程+init方法。
以上就是关于alloc和init以及new方法的底层原理探索,如有疑问或错误之处,请在评论区留言吧!!