1.对象 类对象,元类对象,根对象,根元类对象关系
![](https://img.haomeiwen.com/i1501762/d67e53cc85f8e4a1.png)
直接上代码
![](https://img.haomeiwen.com/i1501762/0f0a46cf1ed7d37b.png)
2.构建对象内部分析
(1)先介绍几个结构体
![](https://img.haomeiwen.com/i1501762/000d8f4b10970bb4.png)
![](https://img.haomeiwen.com/i1501762/b7fe871a1b035518.png)
![](https://img.haomeiwen.com/i1501762/d2c115c7e7ef4ec0.png)
TestObject * obj = [[TestObject alloc]init];
+ (id)alloc {
return _objc_rootAlloc(self);
}
id _objc_rootAlloc(Classcls)
{
return callAlloc(cls, false/*checkNil*/, true/*allocWithZone*/);
}
static ALWAYS_INLINE id
callAlloc(Classcls,boolcheckNil,boolallocWithZone=false)
{
if(slowpath(checkNil && !cls))returnnil;
#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.
booldtor = cls->hasCxxDtor();
idobj = (id)calloc(1, cls->bits.fastInstanceSize());
if(slowpath(!obj))returncallBadAllocHandler(cls);
obj->initInstanceIsa(cls, dtor);
returnobj;
}
else{
// Has ctor or raw isa or something. Use the slower path.
//它会走这个方法
idobj =class_createInstance(cls,0);
if(slowpath(!obj))returncallBadAllocHandler(cls);
returnobj;
}
}
#endif
// No shortcuts available.
if(allocWithZone)return[clsallocWithZone:nil];
return[clsalloc];
}
id
class_createInstance(Classcls,size_textraBytes)
{
return _class_createInstanceFromZone(cls, extraBytes, nil);
}
static __attribute__((always_inline))
id
_class_createInstanceFromZone(Classcls,size_textraBytes,void*zone,
boolcxxConstruct =true,
size_t*outAllocatedSize =nil)
{
if(!cls)returnnil;
assert(cls->isRealized());
// Read class's info bits all at once for performance
boolhasCxxCtor = cls->hasCxxCtor();
boolhasCxxDtor = cls->hasCxxDtor();
boolfast = cls->canAllocNonpointer();
size_tsize = cls->instanceSize(extraBytes);
if(outAllocatedSize) *outAllocatedSize = size;
idobj;
if(!zone && fast) {
obj = (id)calloc(1, size);
if(!obj)returnnil;
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)returnnil;
// 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);
}
returnobj;
}
//获取size
size_tinstanceSize(size_textraBytes) {
size_tsize =alignedInstanceSize() + extraBytes;
// CF框架需要所有对象大小最少是16字节
// CF requires all objects be at least 16 bytes.
if(size <16) size =16;
returnsize;
}
uint32_talignedInstanceSize() {
return word_align(unalignedInstanceSize());
}
uint32_tunalignedInstanceSize() {
assert(isRealized());
return data()->ro->instanceSize;
}
网友评论