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_createInstanceFromZonealloc 的核心作用就是开辟内存,通过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方法,无法调用到自定义的初始化方法