OC
底层研究。主要研究方向包括了:对象和类的具体实现,属性、方法、协议等是如何存储的,方法是如何调用,类和category
是如何加载,weak
是如何实现的等等一些问题objc4
源码(目前最新版)iOS
的开发过程中,使用最频繁的就是alloc
一个对象,那alloc
到底做了些什么?那就让我们从alloc
开始,开启oc
的底层研究之路。Test
类@interface Test : NSObject@end@implementation Test@end- (void)viewDidLoad {[super viewDidLoad];Test *test = [Test alloc];
}
alloc
的实现,发现进去只能看到声明,看不到具体实现。由于我们写的都是高级语言,最终都会编译成汇编。所以我们可以通过汇编来查看具体调用。Debug
-> Debug Workflow
-> Always Show Disassembly
,打开汇编Test *test1 = [Test alloc];
添加断点。alloc
调用的是objc_alloc
方法。然后按住control
键+step into
,执行到objc_alloc
里面去了libobjc.A.dylib
中,调用了_objc_rootAllocWithZone
方法。既然知道方法在lib库中,这个时候我们就进入到objc4
源码中。id
objc_alloc(Class cls)
{return callAlloc(cls, true/*checkNil*/, false/*allocWithZone*/);
}
callAlloc
方法static ALWAYS_INLINE id
callAlloc(Class cls, bool checkNil, bool allocWithZone=false)
{
#if __OBJC2__ // 判断是否是否objc2.0版本,目前所采用都是2.0版本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));
}
#define fastpath(x) (__builtin_expect(bool(x), 1)) // fastpath(x):x很可能为真
#define slowpath(x) (__builtin_expect(bool(x), 0)) // slowpath(x):x很可能为假,为真的概率很小
callAlloc
方法,会调用((id(*)(id, SEL))objc_msgSend)(cls, @selector(alloc));
方法。 objc_msgSend
是iOS中消息转发机制,最终会调用alloc
这个方法_objc_rootAllocWithZone
方法。alloc
方法+ (id)alloc {return _objc_rootAlloc(self);
}
_objc_rootAlloc
方法id
_objc_rootAlloc(Class cls)
{return callAlloc(cls, false/*checkNil*/, true/*allocWithZone*/);
}
callAlloc
方法_objc_rootAllocWithZone
方法callAlloc
方法?为什么alloc
方法需要先调用objc_alloc
然后再调用alloc
。alloc
方法,添加一个hook
方法objc_alloc
。让每第一次走到alloc
方法,都先走到object_alloc
方法。只有走过这个方法后,再去调用真正的alloc
方法。objc_alloc
方法做一些额外操作,比如ARC
相关,类型转换等,方便苹果做一些监控,以及优化。NEVER_INLINE
id
_objc_rootAllocWithZone(Class cls, malloc_zone_t *zone __unused)
{// allocWithZone under __OBJC2__ ignores the zone parameterreturn _class_createInstanceFromZone(cls, 0, nil,OBJECT_CONSTRUCT_CALL_BADALLOC);
}
_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 performancebool hasCxxCtor = cxxConstruct && cls->hasCxxCtor();bool hasCxxDtor = cls->hasCxxDtor();bool fast = cls->canAllocNonpointer();size_t size;// 1. 计算需要初始化的大小size = cls->instanceSize(extraBytes);if (outAllocatedSize) *outAllocatedSize = size;// 2. 开辟对应大小的内存空间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;}// 3. 把开辟的内存和类关联起来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);
}
这个方法是最重要的方法,从实现中可以得知,它主要干了三件事:
cls->instanceSize(extraBytes);
:计算内存大小(id)malloc_zone_calloc((malloc_zone_t *)zone, 1, size);
或者(id)calloc(1, size)
:开辟内存,返回地址指针obj->initInstanceIsa(cls, hasCxxDtor);
或者obj->initIsa(cls);
:把内存和类关联起来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; return size;
}
fastInstanceSize
方法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// 删除由setFastInstanceSize添加的FAST_CACHE_ALLOC_DELTA16 8个字节// 进行16字节对齐return align16(size + extra - FAST_CACHE_ALLOC_DELTA16);}
}
size
是通过_flags & FAST_CACHE_ALLOC_MASK
计算得到的。这里需要我们了解类的具体结构,这里可以简单理解为一个类中成员变量的大小static inline size_t align16(size_t x) {return (x + size_t(15)) & ~size_t(15);
}
alignedInstanceSize
方法// Class's ivar size rounded up to a pointer-size boundary.
uint32_t alignedInstanceSize() const {return word_align(unalignedInstanceSize());
}
unalignedInstanceSize()
// May be unaligned depending on class's ivars.
// 可以根据类的成员变量进行对齐。
uint32_t unalignedInstanceSize() const {ASSERT(isRealized());return data()->ro()->instanceSize;
}
#define WORD_MASK 7UL
static inline uint32_t word_align(uint32_t x) {return (x + WORD_MASK) & ~WORD_MASK;
}
通过调用可知void *zone
传入的是0,所有这里会调用calloc
方法
首先通过instanceSize
计算出内存大小,然后向系统申请对应大小,返回给obj
calloc
具体底层实现,可阅读iOS中calloc和malloc源码分析
void *zone
传入的是0,并且现在是支持Nonpointer
类型isa
,所以会调用initInstanceIsa
方法inline void
objc_object::initInstanceIsa(Class cls, bool hasCxxDtor)
{ASSERT(!cls->instancesRequireRawIsa());ASSERT(hasCxxDtor == cls->hasCxxDtor());initIsa(cls, true, hasCxxDtor);
}
initIsa
方法,具体流程,我们会在isa
这一章节讲解。可参考Runtime源码剖析-对象初始化isa
章节。obj
对象,发现po
出了它对应的类型。说明initInstanceIsa
方法,把内存和类关联起来。alloc
核心方法是_class_createInstanceFromZone
alloc
的核心作用就是开辟内存,通过isa
指针与类进行关联alloc
和init
放在一起使用。[[NSObject alloc] 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;
}
obj
对象本身init
方法更多的是提供给我们一个抽象接口,可以让我们在子类中重写它,达到自定义效果。new
,而不是alloc init
。+ (id)new {return [callAlloc(self, false/*checkNil*/) init];
}
callAlloc
函数,并且调用init
函数。所以可以得出new
等价[alloc init]
new
。原因是有时候会重写init
方法,类似于initWithXXX
。使用new
方法,无法调用到自定义的初始化方法