前言
在面向对象编程中,万物皆对象,在实际编程过程中,[[xxx alloc] init]
是非常普遍的代码,那么一个对象是如何被创建的呢?
大纲
alloc方法底层实现流程?
init方法都做了些什么?
new 与 alloc init
总结
一、alloc实现流程
Person *p = [Person alloc];
在Foundation层我们初始化一个对象需要调用alloc方法,通过查看堆栈信息我们可以大致知道函数调用过程如下:
接下来,结合源码,我们共同探究一下alloc的神秘面纱。
1.objc_alloc
// Calls [cls alloc].
id
objc_alloc(Class cls)
{
return callAlloc(cls, true/*checkNil*/, false/*allocWithZone*/);
}
[Person alloc]
执行后,最先进入的是objc_alloc
函数,在此函数中传入当前类(Person),并且调用callAlloc
函数。
2.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 __OBJC2__
if (slowpath(checkNil && !cls)) return nil;
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));
}
在这里我们也拓展一下其他知识,了解一下objc底层一些特性:
- 先看一下ALWAYS_INLINE
inline 是一种降低函数调用成本的方法,其本质是在调用声明为 inline 的函数时,会直接把函数的实现替换过去,这样减少了调用函数的成本。 是一种以空间换时间的做法。
#define ALWAYS_INLINE inline __attribute__((always_inline))
ALWAYS_INLINE宏会强制开启inline。
- slowpath & fastpath
#define fastpath(x) (__builtin_expect(bool(x), 1))
#define slowpath(x) (__builtin_expect(bool(x), 0))
这两个宏使用__builtin_expect函数
__builtin_expect(EXP, N)
这个指令的意思是EXP==N的概率更大。用于上方就是对于>fastpath(x)
x为真可能性更大,对于>slowpath(x)
x为假可能性更大。
这个指令的作用是允许程序员将最有可能执行的分支告诉编译器,用于优化代码执行效率,提高预读指令的命中率,以减少指令跳转带来的性能下降!
所以我们在分析的时候,以实际为准。
对于下面代码:
if (fastpath(!cls->ISA()->hasCustomAWZ()))
此句代码为判断当前class or superclass 是否有自定义的alloc/allocWithZone 方法实现 ?
如果cls->ISA()->hasCustomAWZ()返回YES,意味着有自定义的allocWithZone方法实现。这个值会存储在metaclass中。
虽然这里是fastpath,但是对于初次创建的类是还没有默认的实现的。所以继续向下执行进入到msgSend消息发送流程,调用alloc函数。
3.alloc
+ (id)alloc {
return _objc_rootAlloc(self);
}
4. _objc_rootAlloc
// Base class implementation of +alloc. cls is not nil.
// Calls [cls allocWithZone:nil].
id
_objc_rootAlloc(Class cls)
{
return callAlloc(cls, false/*checkNil*/, true/*allocWithZone*/);
}
执行到这个过程会再次进入到callAlloc
函数,但是这一次当前类的默认实现已经注册完毕,所以会执行到_objc_rootAllocWithZone
函数中。
5.callAlloc
if (fastpath(!cls->ISA()->hasCustomAWZ())) {
return _objc_rootAllocWithZone(cls, nil);
}
6. _objc_rootAllocWithZone
NEVER_INLINE
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);
}
7. _class_createInstanceFromZone
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);
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);
}
先看一下前面的几个bool值
bool hasCxxCtor = cls->hasCxxCtor();
bool hasCxxDtor = cls->hasCxxDtor();
bool fast = cls->canAllocNonpointer();
hasCxxCtor 判断当前class or superclass 是否有.cxx_construct构造方法的实现;
hasCxxDtor 判断当前class or superclass 是否有.cxx_destruct析构方法的实现;
canAllocNonpointer 是对 isa 的类型的区分,如果一个类和它父类的实例不能使用 isa_t 类型的 isa 的话,返回值为 false。在 Objective-C 2.0 中,大部分类都是支持的;
- 7.1 重要函数:计算所需空间大小:
size_t size = cls->instanceSize(extraBytes);
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;
return size;
}
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);
}
}
static inline size_t align16(size_t x) {
return (x + size_t(15)) & ~size_t(15);
}
计算申请空间大小: 对于继承自NSObject没有任何属性的自定义类而言,默认有个isa结构体。占8字节。
@interface NSObject <NSObject> {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wobjc-interface-ivars"
Class isa OBJC_ISA_AVAILABILITY;
#pragma clang diagnostic pop
}
最终经过align16
函数计算方式:
(8 + 15)& ~15 (等同于>>4再<<4)
最终结果为16的倍数,且最小为16字节(这里的传入的x受类的属性个数的影响)。在Core Foundation 中,需要所有的对象的大小不小于 16 字节。
- 7.2 重要函数:calloc
id obj;
if (zone) {
obj = (id)malloc_zone_calloc((malloc_zone_t *)zone, 1, size);
} else {
obj = (id)calloc(1, size);
}
alloc 开辟内存的地方。
按计算大小通过 calloc()函数为对象分配内存空间, calloc()会默认的把申请出来的空间初始化为0或者nil。(这里的zone基本是不会走的,苹果废弃了zone开辟空间,并且这里zone的入参传入的也是nil)
- 7.3重要函数:initInstanceIsa
inline void
objc_object::initInstanceIsa(Class cls, bool hasCxxDtor)
{
ASSERT(!cls->instancesRequireRawIsa());
ASSERT(hasCxxDtor == cls->hasCxxDtor());
initIsa(cls, true, hasCxxDtor);
}
inline void
objc_object::initIsa(Class cls, bool nonpointer, bool hasCxxDtor)
{
ASSERT(!isTaggedPointer());
if (!nonpointer) {
isa = isa_t((uintptr_t)cls);
} else {
ASSERT(!DisableNonpointerIsa);
ASSERT(!cls->instancesRequireRawIsa());
isa_t newisa(0);
#if SUPPORT_INDEXED_ISA
ASSERT(cls->classArrayIndex() > 0);
newisa.bits = ISA_INDEX_MAGIC_VALUE;
// isa.magic is part of ISA_MAGIC_VALUE
// isa.nonpointer is part of ISA_MAGIC_VALUE
newisa.has_cxx_dtor = hasCxxDtor;
newisa.indexcls = (uintptr_t)cls->classArrayIndex();
#else
newisa.bits = ISA_MAGIC_VALUE;
// isa.magic is part of ISA_MAGIC_VALUE
// isa.nonpointer is part of ISA_MAGIC_VALUE
newisa.has_cxx_dtor = hasCxxDtor;
newisa.shiftcls = (uintptr_t)cls >> 3;
#endif
// This write must be performed in a single store in some cases
// (for example when realizing a class because other threads
// may simultaneously try to use the class).
// fixme use atomics here to guarantee single-store and to
// guarantee memory order w.r.t. the class index table
// ...but not too atomic because we don't want to hurt instantiation
isa = newisa;
}
}
初始化的过程就是对isa_t结构体初始化的过程。
关于Isa类型
Isa类型有如下宏定义
// Define SUPPORT_INDEXED_ISA=1 on platforms that store the class in the isa
// field as an index into a class table.
// Note, keep this in sync with any .s files which also define it.
// Be sure to edit objc-abi.h as well.
#if __ARM_ARCH_7K__ >= 2 || (__arm64__ && !__LP64__)
# define SUPPORT_INDEXED_ISA 1
#else
# define SUPPORT_INDEXED_ISA 0
#endif
// Define SUPPORT_PACKED_ISA=1 on platforms that store the class in the isa
// field as a maskable pointer with other data around it.
#if (!__LP64__ || TARGET_OS_WIN32 || \
(TARGET_OS_SIMULATOR && !TARGET_OS_IOSMAC))
# define SUPPORT_PACKED_ISA 0
#else
# define SUPPORT_PACKED_ISA 1
#endif
// Define SUPPORT_NONPOINTER_ISA=1 on any platform that may store something
// in the isa field that is not a raw pointer.
#if !SUPPORT_INDEXED_ISA && !SUPPORT_PACKED_ISA
# define SUPPORT_NONPOINTER_ISA 0
#else
# define SUPPORT_NONPOINTER_ISA 1
#endif
SUPPORT_INDEXED_ISA 的含义是,如果为 1,则会在 isa field 中存储 class 在 class table 的索引。SUPPORT_PACKED_ISA 为 1 时则是在 isa field 中通过 mask 的方式存储 class 的指针信息。
SUPPORT_NONPOINTER_ISA 用于标记是否支持优化的 isa 指针,其字面含义意思是 isa 的内容不再是类的指针了,而是包含了更多信息,比如引用计数,析构状态,被其他 weak 变量引用情况。
在_class_createInstanceFromZone
中,主要做了3件事,1.计算对象所需的空间大小;2.根据计算大小开辟空间;3.初始化isa,使其与当前对象关联。
至此,一个对象就创建完成了。
我们通过流程图再来回顾一下上面的流程。
二、init函数
通过alloc方法,开辟了所需空间,关联了isa,那么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];
}
包装了 alloc init,允许我们快速的生成一个对象。
四、总结
至此,我们对象的创建就完成了,用一句话总结一下:alloc是孕育的过程
,孕育完成之时,对象的“遗传基因”等信息就已经确定了,init是出生的过程
,允许我们在出生之后进行不同的装配。
我们用一个示例来验收我们上面的学习成果,看示例代码思考底层实现细节。然后运行代码验证答案。
Person *p1 = [Person alloc];
Person *p2 = [p1 init];
Person *p3 = [p1 init];
NSLog(@"%@ - %p - %p",p1,p1,&p1);
NSLog(@"%@ - %p - %p",p2,p2,&p2);
NSLog(@"%@ - %p - %p",p3,p3,&p3);