首先我们来看一段代码:
Person *p1 = [Person alloc];
Person *p2 = [p1 init];
Person *p3 = [p1 init];
Person *p4 = [Person new];
Person *p5 = [p4 init];
NSLog(@"%@ - %@p - %p",p1,p1,&p1);
NSLog(@"%@ - %@p - %p",p2,p2,&p2);
NSLog(@"%@ - %@p - %p",p3,p3,&p3);
NSLog(@"%@ - %@p - %p",p4,p4,&p4);
NSLog(@"%@ - %@p - %p",p5,p5,&p5);
打印结果:
小结:通过上图可以看出,p1,p2,p3指向的是同一个内存空间
,其内容
和 内存地址
是相同
的,但是对象的指针地址是不同的, p4和p5一样。大致可得知init
方法并没有对内存空间做任何的处理,地址指针的创建来自于 alloc、new
方法。
眼神好的同学可能已经发现了,p1,p2,p3对象的指针地址都是0x7开头,即栈区 ,指向0x6的同一个堆内存,并且三个指针地址分别相差8个字节(16进制),这是因为在64位电脑上指针占内存空间为8个字节。同时也证明了栈是高地址向低地址拓展的数据结构,是一块连续的内存的区域。
那么 alloc、init、new底层到底做了一些什么呢?我们一起来探索一下。
一、下载 objc4-781.tar.gz 源码
1、打开源码搜索 alloc { 找到+ (id)alloc的源码实现
2、全局搜索找到_objc_rootAlloc的源码实现
3、全局搜索找到callAlloc的源码实现
4、全局搜索找到_objc_rootAllocWithZone的源码实现
5、全局搜索找到_class_createInstanceFromZone的源码实现
小结:有没有觉得上面的方法很low,而且有些地方你不确定到底走的哪个方法 ,那么有没有可以直接运行并且可添加断点的源码呢?当然是有的,有一位知名的大佬已经帮大家整理好了。传送门:可运行的objc源码
二、话不多说,下载上面可以直接运行的源码
1、断点在此处,保证进去的alloc方法是我想要的,而不是系统的
2、按住依次跳转,看图
3、callAlloc方法分析
callAlloc(Class cls, bool checkNil, bool allocWithZone=false)
{
#if __OBJC2__
if (slowpath(checkNil && !cls)) return nil;//slowpath表示不大可能走这里
if (fastpath(!cls->ISA()->hasCustomAWZ())) {//fastpath表示大概率会走这里
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));
}
slowpath和fastpath是编译器优化,简单点理解:
fastpath(x) : x为真的可能性更大
slowpath(x) : x为假的可能性更大
if(fastpath(xxx))执行 if 后面的语句的机会更大,编译器在编译过程中,会将可能性更大的代码紧跟着前面的代码,从而减少指令跳转带来的性能上的下降。
cls->ISA()->hasCustomAWZ()
表示判断一个类是否有自定义的 +allocWithZone 实现
,这里通过断点调试,是没有自定义的实现所以会调用_objc_rootAllocWithZone方法,继续往下,将来到核心方法。
4、核心方法_class_createInstanceFromZone
_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();//判断当前class或者superclass是否有.cxx_construct 构造方法的实现
bool hasCxxDtor = cls->hasCxxDtor();//判断判断当前class或者superclass是否有.cxx_destruct 析构方法的实现
bool fast = cls->canAllocNonpointer();//标记某个类是否支持优化的isa
size_t size;
size = cls->instanceSize(extraBytes);//***计算开辟空间大小
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);
}
if (slowpath(!obj)) {
if (construct_flags & OBJECT_CONSTRUCT_CALL_BADALLOC) {
return _objc_callBadAllocHandler(cls);
}
return nil;
}
if (!zone && fast) {
obj->initInstanceIsa(cls, hasCxxDtor);
} 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);
}
3个重要方法分析:
第一个:instanceSize(extraBytes) 计算开辟空间大小
inline size_t instanceSize(size_t extraBytes) const {
if (fastpath(cache.hasFastInstanceSize(extraBytes))) {
return cache.fastInstanceSize(extraBytes);
}
size_t size = alignedInstanceSize() + extraBytes;
// CF requires all objects be at least 16 bytes.
if (size < 16) size = 16;//从这里可以看出最小分配内存为16字节
return size;
}
老规矩fastpath大概率执行,走到方法align16(size + extra - FAST_CACHE_ALLOC_DELTA16)
align16就是16位内存对齐,返回内存的大小是16的倍数。这里关于内存对齐可以康康我的另一篇文章 iOS底层源码研究之内存对齐
第二个:obj = (id)calloc(1, size) 向系统申请开辟内存空间,返回地址指针
第三个:obj->initInstanceIsa(cls, hasCxxDtor) 将对象和指针进行关联
总结:alloc底层大致流程
三、init 和new又做了什么呢?
话不多说,直接跳过去
+ (id)init {//类方法
return (id)self;
}
- (id)init {//对象方法
return _objc_rootInit(self);
}
_objc_rootInit(id obj){
return obj;
}
init什么也不做,就是给开发者使用工厂设计模式提供一个接口
+ (id)new {
return [callAlloc(self, false/*checkNil*/) init];
}
new这不就是[alloc init]么
区别:
-
如果子类没有重写父类的init,new会调用父类的init方法
-
如果子类重写了父类的init,new会调用子类重写的init方法
-
如果使用 alloc + 自定义的init,可以帮助我们自定义初始化操作,例如传入一些子类所需参数等,最终也会走到父类的init,相比new而言,扩展性更好,更灵活。
四、补充
1、通过Step into方式查看alloc流程
按住control + 向下箭头跳转
发现首先调用的方法是objc_alloc
2、通过汇编方式查看alloc流程
按上图打开汇编重新断点运行
发现也是先走objc_alloc方法
疑问:alloc在调用alloc方法之前是否还有别的操作
打开源码找到objc_alloc方法,然后关掉汇编
小结:alloc详细流程图
问题:苹果为什么这么设计?