目录
前言
先来看看下面这段代码:
Person* person = [Person alloc];
Person* person1 = [person init];
Person* 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、person1以及person2的指针变量是不同的,但却指向了同一个内存地址,所以内存的申请开辟是在alloc
方法里实现的,init
方法只是生成对象指针并初始化一些信息,并没有对内存空间做任何处理
alloc方法源码探索
1. alloc
方法:
+ (id)alloc {
return _objc_rootAlloc(self);
}
2. _objc_rootAlloc()
方法:
// Base class implementation of +alloc. cls is not nil.
// Calls [cls allocWithZone:nil]. 从OC视角来看,alloc 实际会调用 allocWithZone:
id
_objc_rootAlloc(Class cls)
{
return callAlloc(cls, false/*checkNil*/, true/*allocWithZone*/);
}
3. callAlloc()
方法:
// Call [cls alloc] or [cls allocWithZone:nil], with appropriate
// shortcutting optimizations.
static ALWAYS_INLINE id
callAlloc(Class cls, bool checkNil, bool allocWithZone=false)
{
if (slowpath(checkNil && !cls)) return nil;
// 判断该类是否实现了自定义的 +allocWithZone:,没有则进入 if 条件语句
if (fastpath(!cls->ISA()->hasCustomAWZ(