Runtime源碼

1 self/super與NSObject對(duì)象

self, super不計(jì)算在object的size里面,用class_getInstanceSize看,只比struct多了一個(gè)isa的8個(gè)字節(jié)。

1. self是隱藏參數(shù),在任何一個(gè)實(shí)例方法、類方法中,都可以訪問(wèn)隱藏的局部變量self。

  1. super是編譯器的指令符號(hào)。

2 字節(jié)對(duì)齊

1. iOS中,OC對(duì)象,最小8個(gè)字節(jié)

字節(jié)對(duì)齊,目的:為了兼容、效率。迎合硬件,CPU -> 系統(tǒng)

  1. iOS,64位系統(tǒng)中,

分配空間的時(shí)候:8字節(jié)對(duì)齊。

(x+7)>>3<<3 好讀

(x+7)& ~7 通用(后三位清零)
注意:關(guān)聯(lián)對(duì)象,不屬于成員變量,所以占用字節(jié)為0

2.1 基礎(chǔ)類型字節(jié)占用

指針,占8個(gè)字節(jié)

short,占2個(gè)字節(jié)

int/float,占4個(gè)字節(jié)

long/double,占8個(gè)字節(jié)

2.2 內(nèi)存分配

int age;
double height;
int good;

順序:isa,然后age、good、height
而不是:isa,age、height、good。

3 為什么要有元類

因?yàn)閛c是基于c的語(yǔ)言,c語(yǔ)言中只有結(jié)構(gòu)體,沒(méi)有類,也就沒(méi)有成員方法。

元類可以用來(lái)保存類的方法。

附 類圖 & 主要結(jié)構(gòu)體

1. class繼承自object

2. object持有isa

3. class持有方法列表

4. class與category的組裝關(guān)系,但至少Runtime中,通過(guò)反射,可以直接拿到category中的方法。

5. SideTable與isa的組裝關(guān)系

1 objc_class

//runtime.h
//很多已經(jīng)OBJC2_UNAVAILABLE;
//Object.mm
typedef struct objc_class *Class;
typedef struct objc_object *id;
//NSObject.h
@interface NSObject <NSObject> {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wobjc-interface-ivars"
    Class isa OBJC_ISA_AVAILABILITY;
#pragma clang diagnostic pop
}
//objc-runtime-new.h
struct objc_class : objc_object {
    Class superclass;
    cache_t cache; // formerly cache pointer and vtable
//函數(shù)指針,【相當(dāng)于老版本中objc_method_list *】
    class_data_bits_t bits; // class_rw_t * plus custom rr/alloc flags
    //...
}

struct objc_object {
private:
    isa_t isa;
//...
}

struct cache_t {
    struct bucket_t *_buckets;
    mask_t _mask;
    mask_t _occupied;
public:
    struct bucket_t *buckets();
    mask_t mask();
    mask_t occupied()
//...
}

//class_data_bits_t也是一個(gè)結(jié)構(gòu)體

struct class_data_bits_t {  
 //這個(gè)方法,用來(lái)獲取數(shù)據(jù) 
 class_rw_t *data() { 
         return bits.data();
     }
 //...
}

//class_rw_t也是一個(gè)結(jié)構(gòu)體,rw表示readwrite
struct class_rw_t {
    uint32_t flags;
    uint32_t version;
    const class_ro_t *ro;
    method_array_t methods;
    property_array_t properties;
    protocol_array_t protocols;
    Class firstSubclass;
    Class nextSiblingClass;
    //...
}

2 super結(jié)構(gòu)體

//message.h
/// Specifies the superclass of an instance. 
struct objc_super {
    /// Specifies an instance of a class.
    __unsafe_unretained _Nonnull id receiver;
    /// Specifies the particular superclass of the instance to message. 
#if !defined(__cplusplus) && !__OBJC2__
    /* For compatibility with old objc-runtime.h header */
    __unsafe_unretained _Nonnull Class class;    //OBJC2中已經(jīng)沒(méi)有了!
#else
    __unsafe_unretained _Nonnull Class super_class;
#endif
    /* super_class is the first class to search */
};
#endif

3 isa_t 聯(lián)合體

//objc-private.h
union isa_t {
    isa_t() { }
    isa_t(uintptr_t value) : bits(value) { }
    Class cls;
    uintptr_t bits;

#if defined(ISA_BITFIELD)
    struct {
        ISA_BITFIELD; // defined in isa.h
    };
#endif
}

//ISA_BITFIELD
//isa.h, 
    struct {
      uintptr_t nonpointer : 1;//代表是否有開(kāi)啟指針isa指針優(yōu)化(位域技術(shù)存儲(chǔ)更多信息)
      uintptr_t has_assoc : 1;//是否有設(shè)置關(guān)聯(lián)對(duì)象  
      uintptr_t has_cxx_dtor : 1;//是否有c++析構(gòu)函數(shù)
      uintptr_t shiftcls : 44;//存儲(chǔ)Class或MetaClass的內(nèi)存地址信息
      uintptr_t magic : 6;//驗(yàn)證對(duì)象是否初始化完成
      uintptr_t weakly_referenced : 1;//是否有被弱引用指針指向
      uintptr_t deallocating : 1;//對(duì)象是否正在釋放
//下面兩個(gè)與引用計(jì)數(shù)有關(guān)。
//extra_rc無(wú)法存儲(chǔ)過(guò)大的數(shù)值時(shí),次標(biāo)志位為1,把extra_rc部分的值存儲(chǔ)到一個(gè)全局的SideTable中
      uintptr_t has_sidetable_rc : 1;
      uintptr_t extra_rc : 8//存儲(chǔ)引用計(jì)數(shù)存儲(chǔ) (引用值 = 存儲(chǔ)值 - 1)
    };

4 objc_category

//runtime.h
struct objc_category {
    char * _Nonnull category_name OBJC2_UNAVAILABLE;
    char * _Nonnull class_name OBJC2_UNAVAILABLE;
    struct objc_method_list * _Nullable instance_methods OBJC2_UNAVAILABLE;
    struct objc_method_list * _Nullable class_methods OBJC2_UNAVAILABLE;
    struct objc_protocol_list * _Nullable protocols OBJC2_UNAVAILABLE;
}  

5 SideTable

源碼的數(shù)據(jù)結(jié)構(gòu)不是常見(jiàn)類型,可以先看下原理iOS Runtime

Objective-C runtime機(jī)制(7)——SideTables, SideTable, weak_table, weak_entry_t

5.1 SideTables,hash數(shù)組

5.2 SideTable,入口


truct SideTable {

    spinlock_t slock; // 自旋鎖,防止多線程訪問(wèn)沖突

    RefcountMap refcnts; // 對(duì)象引用計(jì)數(shù)map

    weak_table_t weak_table; // 對(duì)象弱引用map

}

5.3 RefcountMap,真正的計(jì)數(shù)表,結(jié)構(gòu)是KV

typedef objc::DenseMap<DisguisedPtr<objc_object>,size_t,true> RefcountMap;
//參數(shù)含義:
//DisguisedPtr<objc_object>表示object
//size_t表示計(jì)數(shù)值
//true,表示value==0時(shí),是否自動(dòng)釋放掉響應(yīng)的hash節(jié)點(diǎn)。

5.4 weak_talbe_t, 真正保存弱引用的表

weakentry_t,key-value

struct weak_table_t {
    weak_entry_t *weak_entries; // 動(dòng)態(tài)hash數(shù)組,用來(lái)存儲(chǔ)弱引用對(duì)象的相關(guān)信息weak_entry_t
    size_t num_entries; // weak_entries數(shù)組中的元素個(gè)數(shù)
    uintptr_t mask; // hash數(shù)組長(zhǎng)度-1,不是元素個(gè)數(shù)。(這里處理沖突,是用的index+1,而不是拉鏈法,有可能index=0,5的元素先來(lái)了,此時(shí)數(shù)組長(zhǎng)度為6,元素個(gè)數(shù)為2)
    uintptr_t max_hash_displacement; // hash沖突相關(guān),這里處理沖突,是用的index+1,而不是拉鏈法
};

#define WEAK_INLINE_COUNT 4
#define REFERRERS_OUT_OF_LINE 2

struct weak_entry_t {
    DisguisedPtr<objc_object> referent; // 被弱引用的對(duì)象
    // 引用該對(duì)象的對(duì)象列表,聯(lián)合。 引用個(gè)數(shù)小于4,用inline_referrers數(shù)組。 用個(gè)數(shù)大于4,用動(dòng)態(tài)數(shù)組weak_referrer_t *referrers
    union {
        struct {
            weak_referrer_t *referrers; // 弱引用該對(duì)象的對(duì)象指針地址的hash數(shù)組
            uintptr_t out_of_line_ness : 2; // 是否使用動(dòng)態(tài)hash數(shù)組標(biāo)記位
            uintptr_t num_refs : PTR_MINUS_2; // referrers數(shù)組中的元素個(gè)數(shù)
            uintptr_t mask; 
            uintptr_t max_hash_displacement; 
        };
        struct {
            // out_of_line_ness field is low bits of inline_referrers[1]
            weak_referrer_t inline_referrers[WEAK_INLINE_COUNT];
        };
    };
    bool out_of_line() {
        return (out_of_line_ness == REFERRERS_OUT_OF_LINE);
    }
    weak_entry_t& operator=(const weak_entry_t& other) {
        memcpy(this, &other, sizeof(other));
        return *this;
    }
    weak_entry_t(objc_object *newReferent, objc_object **newReferrer)
        : referent(newReferent) // 構(gòu)造方法,里面初始化了靜態(tài)數(shù)組
    {
        inline_referrers[0] = newReferrer;
        for (int i = 1; i < WEAK_INLINE_COUNT; i++) {
            inline_referrers[i] = nil;
        }
    }
};
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容