iOS 开发中所有的类都是继承自 NSObject 来的(除了个别的, 比如 NSProxy). 也几乎没有类会去重写 alloc 方法, 接下来, 就以 NSObject 为例分析一下
创建一个对象的过程都要 alloc, 例如 [NSObject alloc];
alloc 中发生了什么呢?
ps: 下载源代码的同学, 打开之前先把 old 文件删掉, 要不然一会儿又到old 文件里面去了, 心累
// https://opensource.apple.com/source/objc4/objc4-709/runtime/NSObject.mm.auto.html
+(id)alloc {
return _objc_rootAlloc(self);
}
这里直接跳转到 _objc_rootAlloc
了
// 同上文件, 这里略微整理了一下
id _objc_rootAlloc(Class cls)
{
return callAlloc(cls, false/*checkNil*/, true/*allocWithZone*/);
}
继续
// 同上文件
static id
callAlloc(Class cls, bool checkNil, bool allocWithZone=false)
{
if (slowpath(checkNil && !cls)) return nil;
#if __OBJC2__
if (fastpath(!cls->ISA()->hasCustomAWZ())) {
// No alloc/allocWithZone implementation. Go straight to the allocator.
// fixme store hasCustomAWZ in the non-meta class and
// add it to canAllocFast's summary
if (fastpath(cls->canAllocFast())) {
// No ctors, raw isa, etc. Go straight to the metal.
bool dtor = cls->hasCxxDtor();
id obj = (id)calloc(1, cls->bits.fastInstanceSize());
if (slowpath(!obj)) return callBadAllocHandler(cls);
obj->initInstanceIsa(cls, dtor);
return obj;
}
else {
// Has ctor or raw isa or something. Use the slower path.
id obj = class_createInstance(cls, 0);
if (slowpath(!obj)) return callBadAllocHandler(cls);
return obj;
}
}
#endif
// No shortcuts available.
if (allocWithZone) return [cls allocWithZone:nil];
return [cls alloc];
}
slowpath 和 fastpath 是一个编译器优化的东西, 我们这里分析源代码就直接忽略了.
#if __OBJC2__
这个判断一定为真, 现在用的都是 objc2.0 了
精简一下代码
static id callAlloc(Class cls, bool checkNil, bool allocWithZone=false)
{
if (checkNil && !cls) return nil;
if (!cls->ISA()->hasCustomAWZ()) {
// No alloc/allocWithZone implementation. Go straight to the allocator.
// fixme store hasCustomAWZ in the non-meta class and
// add it to canAllocFast's summary
if (fastpath(cls->canAllocFast())) {
// No ctors, raw isa, etc. Go straight to the metal.
bool dtor = cls->hasCxxDtor();
id obj = (id)calloc(1, cls->bits.fastInstanceSize());
if (slowpath(!obj)) return callBadAllocHandler(cls);
obj->initInstanceIsa(cls, dtor);
return obj;
}
else {
// Has ctor or raw isa or something. Use the slower path.
id obj = class_createInstance(cls, 0);
if (slowpath(!obj)) return callBadAllocHandler(cls);
return obj;
}
}
// No shortcuts available.
if (allocWithZone) return [cls allocWithZone:nil];
return [cls alloc];
}
然后根据之前传过来的参数, checkNil 是 false, 第一个 if 就没用了, 第二个 if , 如果有自定义的 allocWithZone 就不使用这下面默认的了, 这里是没有自定义的.
canAllocFast, 目前所有的类都是返回 false. 所以再精简一下
static id callAlloc(Class cls, bool checkNil, bool allocWithZone=false)
{
// Has ctor or raw isa or something. Use the slower path.
id obj = class_createInstance(cls, 0);
if (slowpath(!obj)) return callBadAllocHandler(cls);
return obj;
}
这就很简单了
第一句创建对象, 第二句错误处理, 然后就返回了
//https://opensource.apple.com/source/objc4/objc4-709/runtime/objc-runtime-new.mm.auto.html
id class_createInstance(Class cls, size_t extraBytes)
{
return _class_createInstanceFromZone(cls, extraBytes, nil);
}
继续
static id _class_createInstanceFromZone(Class cls, size_t extraBytes, void *zone,
bool cxxConstruct = true,
size_t *outAllocatedSize = nil)
{
if (!cls) return nil;// 首先是判断是否为空
assert(cls->isRealized());// 检查是否已经realize 了
// Read class's info bits all at once for performance
bool hasCxxCtor = cls->hasCxxCtor();// 对 C++ 混编的支持, 这里略过
bool hasCxxDtor = cls->hasCxxDtor();// 对 C++ 混编的支持, 这里略过
bool fast = cls->canAllocNonpointer();// objc 2.0 都是返回 true
size_t size = cls->instanceSize(extraBytes); // 这一步是获取对象大小的, 这样才能分配合适的空间保存对象. 稍后再讲
if (outAllocatedSize) *outAllocatedSize = size;
//这下面开始创建对象了
id obj;
if (!zone && fast) {
// 基本都是走这一个分支
obj = (id)calloc(1, size); // 分配空间, calloc 会把分配好的内存空间全部值为0, 这就是为什么没有初始化的属性都是0, nil, false 的原因
if (!obj) return nil;
obj->initInstanceIsa(cls, hasCxxDtor);// 初始化
}
else {
//这个分支下面可以跳过不用看了
if (zone) {
obj = (id)malloc_zone_calloc ((malloc_zone_t *)zone, 1, size);
} else {
obj = (id)calloc(1, size);
}
if (!obj) return nil;
// Use raw pointer isa on the assumption that they might be
// doing something weird with the zone or RR.
obj->initIsa(cls);
}
// 混编的处理部分, 这里略过
if (cxxConstruct && hasCxxCtor) {
obj = _objc_constructOrFree(obj, cls);
}
return obj;
}
其中检查 isRealized 的部分可以看这篇文章
fast 部分引用一下别人的
而 fast,是对 isa 的类型的区分,如果一个类的实例不能使用 isa_t 类型的 isa 的话,fast 就为 false,但是在 Objective-C 2.0 中,大部分类都是支持的。关于 isa 的类型,可以看看「Objective-C 小记(1)Messaging」和「Objective-C 小记(2)对象 2.0」。
获取对象尺寸的部分, 借用一些别人写的
不难看出就是从 cls 的 ro 中获得 instanceSize 然后将它对齐,并加上 extraBytes,最后 Core Foundation 需要对象至少要有 16 字节,小于 16 的统统返回 16。
//https://opensource.apple.com/source/objc4/objc4-709/runtime/objc-runtime-new.mm.auto.html
// May be unaligned depending on class's ivars.
uint32_t unalignedInstanceSize() {
assert(isRealized());
return data()->ro->instanceSize;
}
// Class's ivar size rounded up to a pointer-size boundary.
uint32_t alignedInstanceSize() {
return word_align(unalignedInstanceSize());
}
size_t instanceSize(size_t extraBytes) {
size_t size = alignedInstanceSize() + extraBytes;
// CF requires all objects be at least 16 bytes.
if (size < 16) size = 16;
return size;
}
初始化部分, 去掉 assert 之后, 其实就是使用initIsa 进行初始化.
//https://opensource.apple.com/source/objc4/objc4-709/runtime/objc-object.h.auto.html
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) {// nonpointer 这个参数是 true
isa.cls = cls;
} else {
assert(!DisableNonpointerIsa);
assert(!cls->instancesRequireRawIsa());
isa_t newisa(0);// 创建一个 newisa
#if SUPPORT_INDEXED_ISA
// 这个宏, 是判断由这个宏判断的, __ARM_ARCH_7K__
// 网上找了一下资料, 应该是 apple watch 会走这个代码
// 直接去看 else 部分
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 初始化
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;//将位移(shift)后的 cls 存入 shiftcls(类指针按照 8 字节对齐,所以最后三位一定是 0,所以可以右移三位来节省位的使用)
#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, 完成了
isa = newisa;
}
}
最后总结一下, 这么多的代码, 其实大部分都是跳来跳去的,
这里去掉一些判断, 断言, 跳转这些, 直接看一下实际调用的代码
+ (id)alloc {
return _objc_rootAlloc(self);
}
id _objc_rootAlloc(Class cls) {
size_t size = word_align(cls->data()->ro->instanceSize);// 获取对象大小
id obj = (id)calloc(1, size); // 分配内存
isa_t newisa(0);
newisa.bits = ISA_MAGIC_VALUE;
newisa.shiftcls = (uintptr_t)cls >> 3;
obj->isa = newisa;// 保存 isa
return obj;
}
实际上就三步, 获取大小, 分配内存, 保存 isa 就完了.其实也是很简单的对吧!
部分源自于 KylinRoc 的文章Objective-C 小记(6)alloc & init