#if __OBJC2__ // fastpath 表示if条件中为1的可能性较大 // 如果类没有自定义的allocwithzone方法 if (fastpath(!cls->ISA()->hasCustomAWZ())) { // cls 是否可以快速创建 if (fastpath(cls->canAllocFast())) { // No ctors, raw isa, etc. Go straight to the metal. // cls是否有c++销毁方法 dtor = destructor bool dtor = cls->hasCxxDtor(); // calloc 在内存中动态地分配 1 个长度为 cls->bits.fastInstanceSize() 的连续空间 id obj = (id)calloc(1, cls->bits.fastInstanceSize()); // 如果obj为空 类初始化失败 报错 attempt to allocate object of class '%s' failed if (slowpath(!obj)) return callBadAllocHandler(cls); // 调用初始化对象isa方法 obj->initInstanceIsa(cls, dtor); return obj; } else { // Has ctor or raw isa or something. Use the slower path. // 调用class_createInstance创建对象 id obj = class_createInstance(cls, 0); // 如果对象为空 那么直接报错 if (slowpath(!obj)) return callBadAllocHandler(cls); return obj; } } #endif
// No shortcuts available. // alloc 方法会进一步调用allocwithzone方法 if (allocWithZone) return [cls allocWithZone:nil]; // 正常情况不会走到这里 想到与一个递归? return [cls alloc]; }
// Read class's info bits all at once for performance // 是否有自定义的创建方法 bool hasCxxCtor = cxxConstruct && cls->hasCxxCtor(); // 是否有自定义的销毁方法 bool hasCxxDtor = cls->hasCxxDtor(); // canAllocNonpointer:class's instances requires raw isa // #define FAST_CACHE_REQUIRES_RAW_ISA (1<<13) // 是否是 isa_t 类型的 isa bool fast = cls->canAllocNonpointer();
id obj; // 新创建一个obj 并指向一块新创建的内存空间 if (zone) { obj = (id)malloc_zone_calloc((malloc_zone_t *)zone, 1, size); } else { obj = (id)calloc(1, size); } // 如果对象创建失败 obj = nil if (slowpath(!obj)) { if (construct_flags & OBJECT_CONSTRUCT_CALL_BADALLOC) { return _objc_callBadAllocHandler(cls); } returnnil; }
// isa如果是isa_t类型 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. // isa是cls类型 obj->initIsa(cls); } // 如果没有自定义构建方法 if (fastpath(!hasCxxCtor)) { return obj; } // 自定义构建方法调用 construct_flags |= OBJECT_CONSTRUCT_FREE_ONFAILURE; return object_cxxConstructFromClass(obj, cls, construct_flags); }
我们在看下这个方法中用到的几个方法:
hasCxxDtor
1 2 3 4 5 6 7 8 9 10 11 12
bool hasCxxDtor() { // addSubclass() propagates this flag from the superclass. assert(isRealized()); return bits.hasCxxDtor(); }
// 递归调用对象的C++构造方法,从基类到子类的构造方法 id object_cxxConstructFromClass(id obj, Class cls, int flags) { ASSERT(cls->hasCxxCtor()); // required for performance, not correctness
id (*ctor)(id); Class supercls;
supercls = cls->superclass;
// Call superclasses' ctors first, if any. // 如果父类有C++构造方法 if (supercls && supercls->hasCxxCtor()) { // 调用父类构造方法 bool ok = object_cxxConstructFromClass(obj, supercls, flags); // 父类构造方法失败 返回nil if (slowpath(!ok)) returnnil; // some superclass's ctor failed - give up }
// Find this class's ctor, if any. // 父类构造方法调用完成后调用当前类的SEL_cxx_construct方法 ctor = (id(*)(id))lookupMethodInClassAndLoadCache(cls, SEL_cxx_construct); // 如果当前类的构造为转发方法 那么直接返回 表示没有对应实现 if (ctor == (id(*)(id))_objc_msgForward_impcache) return obj; // no ctor - ok
// Call this class's ctor. if (PrintCxxCtors) { _objc_inform("CXX: calling C++ constructors for class %s", cls->nameForLogging()); } // 调用构造方法 传入参数obj if (fastpath((*ctor)(obj))) return obj; // ctor called and succeeded - ok
supercls = cls->superclass; // this reload avoids a spill on the stack
// This class's ctor was called and failed. // Call superclasses's dtors to clean up. if (supercls) object_cxxDestructFromClass(obj, supercls); if (flags & OBJECT_CONSTRUCT_FREE_ONFAILURE) free(obj); if (flags & OBJECT_CONSTRUCT_CALL_BADALLOC) { return _objc_callBadAllocHandler(cls); } returnnil; }
/* "Unknown" includes non-object ivars and non-ARC non-__weak ivars "Strong" includes ARC __strong ivars "Weak" includes ARC and new MRC __weak ivars "Unretained" includes ARC __unsafe_unretained and old GC+MRC __weak ivars */ typedefenum { objc_ivar_memoryUnknown, // unknown / unknown objc_ivar_memoryStrong, // direct access / objc_storeStrong objc_ivar_memoryWeak, // objc_loadWeak[Retained] / objc_storeWeak objc_ivar_memoryUnretained // direct access / direct access } objc_ivar_memory_management_t;
下面我们来详细的了解下这其中的区别:
__strong
上面看到的
1
Person *stu = [[Person alloc] init];
实际上可以翻译成:
1
__strong Person *stu = [[Person alloc] init];
那么__strong都做了什么呢?我们直接去看下objc_storeStrong方法都做了什么:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
void objc_storeStrong(id *location, id obj) { id prev = *location; // 先判断之前的值和要新赋值的对象地址是否相同 if (obj == prev) { return; } // 执行retain操作 保留新值 objc_retain(obj); *location = obj; // 释放旧值 objc_release(prev); }
/*********************************************************************** * _class_getFreedObjectClass. Return a pointer to the dummy freed * object class. Freed objects get their isa pointers replaced with * a pointer to the freedObjectClass, so that we can catch usages of * the freed object. **********************************************************************/ static Class _class_getFreedObjectClass(void) { return (Class)freedObjectClass; }
if (anObject->ISA() == _objc_getFreedObjectClass ()) __objc_error(anObject, "reallocating freed object");
重新分配已释放对象的空间,这也作证了我们上面描述的。
objc_clear_deallocating
1 2 3 4 5 6 7 8 9 10 11 12 13 14
inlinevoid objc_object::clearDeallocating() { if (slowpath(!isa.nonpointer)) { // Slow path for raw pointer isa. sidetable_clearDeallocating(); } elseif (slowpath(isa.weakly_referenced || isa.has_sidetable_rc)) { // Slow path for non-pointer isa with weak refs and/or side table data. clearDeallocating_slow(); }
// clear any weak table items // clear extra retain count and deallocating bit // (fixme warn or abort if extra retain count == 0 ?) table.lock(); RefcountMap::iterator it = table.refcnts.find(this); if (it != table.refcnts.end()) { if (it->second & SIDE_TABLE_WEAKLY_REFERENCED) { weak_clear_no_lock(&table.weak_table, (id)this); } table.refcnts.erase(it); } table.unlock(); }