参考底层源码:objc4-818.2
流程:
示例代码:
Person *per = [Person alloc];
-第1步:
_objc_rootAlloc(Class cls) {
return callAlloc(cls, false/*checkNil*/, true/*allocWithZone*/);
}
-第2步:
_objc_rootAlloc(Class cls) {
return callAlloc(cls, false/*checkNil*/, true/*allocWithZone*/);
}
-第3步:
// Call [cls alloc] or [cls allocWithZone:nil], with appropriate
// shortcutting optimizations.
static ALWAYS_INLINE id callAlloc(Class cls, bool checkNil, bool allocWithZone=false)
{
#if __OBJC2__
//如果checkNil需要检验nil为yes && cls == nil => return 不处理
if (slowpath(checkNil && !cls)) return nil;
//有没有实现Alloc 或者 AllocWithZone,如果没有实现实现就会进入实现部分,继承NSObject、NSProxy的对象都是false
if (fastpath(!cls->ISA()->hasCustomAWZ())) {
return _objc_rootAllocWithZone(cls, nil); //内部调用_class_createInstanceFromZone,接下来看它的实现
}
#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 cls, malloc_zone_t *zone __unused)
{
// allocWithZone under __OBJC2__ ignores the zone parameter
return _class_createInstanceFromZone(cls, 0, nil, OBJECT_CONSTRUCT_CALL_BADALLOC);
}
-第五步:
/***********************************************************************
* class_createInstance
* fixme
* Locking: none
*
* **Note**: this function has been carefully written so that the fastpath
* takes no branch.
************************************************************************ ** **/
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);//根据默认内存0设置对象的内存
if (outAllocatedSize) *outAllocatedSize = size;
id obj;
if (zone) {//根据型参数不会走
obj = (id)malloc_zone_calloc((malloc_zone_t *)zone, 1, size);
} else {//调用c语言的calloc,分配内存
obj = (**id**)calloc(1, size);
}
//如果obj内存分配失败,抛出异常后者返回nil
if (slowpath(!obj)) {
if (construct_flags & OBJECT_CONSTRUCT_CALL_BADALLOC) {
return _objc_callBadAllocHandler(cls);
}
return nil;
}
if (!zone && fast) {/*如果不使用allocZone && 需要快速建立*/
obj->initInstanceIsa(cls, hasCxxDtor);
} else { /*直接初始化isa,一个ias默认是8字节,16位*/
// 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);
}