這里是有篇文章對于Obj 對象生成過程進行詳細說明的文章,個人感覺很不錯
Objc 對象的今生今世
我把源碼從蘋果官方上下載并提交到github上的,因為蘋果官方頁面實在太慢了…
這是NSObject.mm源碼的github地址,點擊跳轉(zhuǎn)
alloc
首先看下alloc
// objc4/objc4-706/runtime/NSObject.mm
+ (id)alloc {
return _objc_rootAlloc(self);
}
id _objc_rootAlloc(Class cls)
{
return callAlloc(cls, false/*checkNil*/, true/*allocWithZone*/);
}
說明一下callAlloc的三個參數(shù)
- cls:類信息(如NSString)
- checkNil:是否需要檢查cls為不為nil
- allocWithZone:是否使用NSZone,如果直接調(diào)用alloc的話,系統(tǒng)會在默認的NSZone里面分配內(nèi)存。
進入 callAlloc的實現(xiàn):
// Call [cls alloc] or [cls allocWithZone:nil], with appropriate
// shortcutting optimizations.
static ALWAYS_INLINE id callAlloc(Class cls, bool checkNil, bool allocWithZone=false)
{
if (checkNil && !cls) return nil;
#if __OBJC2__
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 (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 (!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 (!obj) return callBadAllocHandler(cls);
return obj;
}
}
#endif
// No shortcuts available.
if (allocWithZone) return [cls allocWithZone:nil];
return [cls alloc];
}
首先 #if __ OBJC2 __ 這個表示object-c 2.0 版本才有的功能
這里代碼比較多,我們先看看cls->ISA()->hasCustomAWZ(),源碼在這
// objc-runtime-new.h
// class or superclass has default alloc/allocWithZone: implementation
// Note this is is stored in the metaclass.
bool hasCustomAWZ() {
return ! bits.hasDefaultAWZ();
}
bool hasDefaultAWZ( ) {
return data()->flags & RW_HAS_DEFAULT_AWZ;
}
bool canAllocFast() {
return false;
}
RW_HAS_DEFAULT_AWZ 這個是用來標示當前的class或者是superclass是否有默認的alloc/allocWithZone。
所以這里hasDefaultAWZ( )方法是用來判斷當前class是否有默認的allocWithZone。
這里代碼比較繞口,這樣改寫一下
if (! cls->ISA()->hasCustomAWZ() )
轉(zhuǎn)變 ->
if( bits.hasDefaultAWZ()) )
轉(zhuǎn)變 ->
if( data()->flags & RW_HAS_DEFAULT_AWZ )
這樣看就清晰了,這句話就是判斷我們或者superclass沒有在 重寫 alloc / allocWithZone方法,如果我們已經(jīng)重寫,則系統(tǒng)調(diào)用我們的方法。鑒于NSZone已經(jīng)廢棄了,所以基本是在判斷alloc。
關(guān)于NSZone的,可以看我這篇文章的后半部分(NSZone源碼解析):http://www.itdecent.cn/p/633f2b1c5dd3
另外,可能有人會在源碼注意到,canAllocFast和hasDefaultAWZ都是有另外一種實現(xiàn)的
// objc-runtime-new.h
#if FAST_HAS_DEFAULT_AWZ
bool hasDefaultAWZ() {
return getBit(FAST_HAS_DEFAULT_AWZ);
}
...
#if FAST_ALLOC
bool canAllocFast() {
return bits &; FAST_ALLOC;
}
...
這里為什么沒有寫出來呢?
因為,需要注意這兩個方法是有編譯條件的
#if FAST_ALLOC
#if FAST_HAS_DEFAULT_AWZ
條件需要有FAST_ALLOC 和 FAST_HAS_DEFAULT_AWZ這兩個宏定義,而這兩個在 objc-runtime-new.h 有定義
// objc-runtime-new.h
// Values for class_rw_t->flags or class_t->bits
// These flags are optimized for retain/release and alloc/dealloc
// 64-bit stores more of them in class_t->bits to reduce pointer indirection.
#if !__LP64__
...
#elif 1
...
#else
// summary bit for fast alloc path: !hasCxxCtor and
// !instancesRequireRawIsa and instanceSize fits into shiftedSize
// hasCxxCtor是判斷當前class或者superclass 是否有.cxx_construct構(gòu)造方法的實現(xiàn)。
// FAST_ALLOC means
// FAST_HAS_CXX_CTOR is set
// FAST_REQUIRES_RAW_ISA is not set
// FAST_SHIFTED_SIZE is not zero
// FAST_ALLOC does NOT check FAST_HAS_DEFAULT_AWZ because that
// bit is stored on the metaclass.
#define FAST_ALLOC (1UL<<50)
// class or superclass has default alloc/allocWithZone: implementation
// Note this is is stored in the metaclass.
#define FAST_HAS_DEFAULT_AWZ (1UL<<48)
#end
首先 if !__ LP64 __ 是處理32位系統(tǒng)的,這里暫時不考慮,然后這里需要注意的是 elif 1,就是else if(1) 的簡寫!
也就是說,#else 不會被編譯了!那么上面兩個條件 FAST_ALLOC 和 FAST_HAS_DEFAULT_AWZ就不成立了!
在 objc-runtime-new.h 繞了好多源碼,現(xiàn)在再回到 alloc 和 allocWithZone 這兩個方法的實現(xiàn)
+ (id)alloc {
return _objc_rootAlloc(self);
}
// Replaced by ObjectAlloc
+ (id)allocWithZone:(struct _NSZone *)zone {
return _objc_rootAllocWithZone(self, (malloc_zone_t *)zone);
}
id _objc_rootAlloc(Class cls)
{
return callAlloc(cls, false/*checkNil*/, true/*allocWithZone*/);
}
id _objc_rootAllocWithZone(Class cls, malloc_zone_t *zone)
{
id obj;
#if __OBJC2__
// allocWithZone under __OBJC2__ ignores the zone parameter
(void)zone;
obj = class_createInstance(cls, 0);
#else
if (!zone || UseGC) {
obj = class_createInstance(cls, 0);
}
else {
obj = class_createInstanceFromZone(cls, 0, zone);
}
#endif
if (!obj) obj = callBadAllocHandler(cls);
return obj;
}
id class_createInstance(Class cls, size_t extraBytes)
{
return _class_createInstanceFromZone(cls, extraBytes, nil);
}
static ALWAYS_INLINE 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];
}
到這里就可以看明白,alloc 和 allocWithZone 基本是靠這兩個方法:class_createInstance 和 initInstanceIsa 進行初始化Objc對象,那么我們接下來再看看這兩個方法是干什么的
先看看 initInstanceIsa
// objc-object.h
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) {
isa.cls = cls;
} else {
assert(!DisableNonpointerIsa);
assert(!cls->instancesRequireRawIsa());
isa_t newisa(0);
#if SUPPORT_INDEXED_ISA
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.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;
#endif
isa = newisa;
}
}
initInstanceIsa 里面是初始化 isa 指針的操作。
再看看class_createInstance
// objc-runtime-new.mm
id class_createInstance(Class cls, size_t extraBytes)
{
return _class_createInstanceFromZone(cls, extraBytes, nil);
}
id class_createInstanceFromZone(Class cls, size_t extraBytes, void *zone)
{
return _class_createInstanceFromZone(cls, extraBytes, zone);
}
static __attribute__((always_inline))
id _class_createInstanceFromZone(Class cls, size_t extraBytes, void *zone,
bool cxxConstruct = true,
size_t *outAllocatedSize = nil)
{
if (!cls) return nil;
assert(cls->isRealized());
// Read class's info bits all at once for performance
bool hasCxxCtor = cls->hasCxxCtor();
bool hasCxxDtor = cls->hasCxxDtor();
bool fast = cls->canAllocNonpointer();
size_t size = cls->instanceSize(extraBytes);
if (outAllocatedSize) *outAllocatedSize = size;
id obj;
if (!zone && fast) {
obj = (id)calloc(1, size);
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;
}
class_createInstance 在初始化內(nèi)存之后,也是調(diào)用initInstanceIsa或者initIsa進行isa指針的設(shè)置。
那么就是說 alloc 和 allocWithZone 到最后做的都是同一件事(當然,中間有很多步操作,到時可以再細化描述一下)。
列舉下 alloc 整個調(diào)用流程
- alloc / allocWithZone
- class_createInstance / initInstanceIsa
- calloc (這里才開始分配內(nèi)存)
- initIsa (初始化isa指針里面的內(nèi)容)
init
init的代碼相對簡單,代碼里面只是返回self
// NSObject.mm
// Replaced by CF (throws an NSException)
+ (id)init { // 類方法
return (id)self;
}
- (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;
}
最后列舉下OC對象的四種狀態(tài):
- 創(chuàng)建并持有對象:alloc init
- 持有對象:retain、copy
- 釋放對象:release
- 廢棄對象:dealloc