iOS底層原理 - 探尋Runtime本質(zhì) 之 isa

面試題引發(fā)的思考:

Q: 簡述isa指針?

  • __arm64__架構(gòu)開始,isa指針:
  • 不只是存儲了 class對象meta-class對象 的地址;
  • 而是使用 共用體結(jié)構(gòu) 存儲了更多信息:
    其中 shiftcls 存儲了 class對象meta-class對象 的地址;
    需要 shiftclsISA_MASK 進行 按位& 運算取出。

Objective-C 擴展了 C 語言,并加入了面向?qū)ο筇匦院?Smalltalk 式的消息傳遞機制。而這個擴展的核心是一個用 C 和 編譯語言 寫的 Runtime 庫。它是 Objective-C 面向?qū)ο蠛蛣討B(tài)機制的基石。

要想學(xué)習Runtime,首先要了解它底層的一些常用數(shù)據(jù)結(jié)構(gòu),比如isa指針:

iOS底層原理 - OC對象的本質(zhì)(二)可知:

  • 每個OC對象都有一個isa指針;
  • instance對象的isa指向class對象;
  • class對象的isa指向meta-class對象;
  • OC對象的isa指針并不是直接指向class對象或者meta-class對象,而是需要&ISA_MASK通過位運算才能獲取到類對象或者元類對象的地址;
    a> 在__arm64__架構(gòu)之前,isa就是一個普通的指針,存儲著Class對象、Meta-Class對象的內(nèi)存地址;
    b> 從__arm64__架構(gòu)開始,對isa進行了優(yōu)化,變成了一個共用體(union)結(jié)構(gòu),還使用位域來存儲更多的信息。

進入OC源碼查看isa指針,進行更深入的了解:

isa結(jié)構(gòu)

由上圖可知:
isa指針其實是一個isa_t類型的共用體;
此共用體中包含一個結(jié)構(gòu)體;
此結(jié)構(gòu)體內(nèi)部定義了若干變量,變量后面的值則表示該變量占用的位數(shù),即位域。

接下來一步步分析共用體的優(yōu)勢。


(1) 探究

// TODO: -----------------  Person類  -----------------
@interface Person : NSObject
// 聲明屬性,系統(tǒng)會自動生成成員變量
@property (nonatomic, assign, getter=isTall) BOOL tall;
@property (nonatomic, assign, getter=isRich) BOOL rich;
@property (nonatomic, assign, getter=isHandsome) BOOL handsome;
@end

@implementation Person
@end

// TODO: -----------------  main  -----------------
int main(int argc, const char * argv[]) {
    @autoreleasepool {
        Person *person  = [[Person alloc] init];
        person.tall = YES;
        person.rich = NO;
        person.handsome = YES;
        NSLog(@"%zd", class_getInstanceSize([Person class]));
     }
    return 0;
}

// 打印結(jié)果
Demo[1234:567890] 16

由以上代碼可知:
isa指針占8個字節(jié),3個BOOL類型的分別占1個字節(jié),一共11個字節(jié)。由于內(nèi)存對齊原則,所以Person類對象所占內(nèi)存應(yīng)該為16個字節(jié)。

BOOL值包含01,只需要1個二進制位就可以表示出來,而現(xiàn)在需要占用1個字節(jié)共8個二進制位。
可以使用1個字節(jié)中的3個二進制位表示3個BOOL值,這樣可以很大程度上節(jié)省內(nèi)存空間。

如果聲明屬性,系統(tǒng)就會自動生成成員變量,占用的內(nèi)存會大于1位;所以不可以聲明屬性,需要手動實現(xiàn)每個屬性的set方法和get方法。

現(xiàn)在添加一個char類型的成員變量,char變量占用一個字節(jié)(8位)的內(nèi)存空間,使用最后3位來存儲3個BOOL值。

1個char值存儲3個BOOL值

(2) 位運算

  1. 補碼(負數(shù)是以補碼的形式表示)
    十進制正整數(shù)轉(zhuǎn)換為二進制數(shù):除2取余即可;
    十進制負整數(shù)轉(zhuǎn)換為二進制數(shù):除2取余,取反加1;
// -10用二進制表示
0b0000 0000 0000 1010 -(10除2取余)
0b1111 1111 1111 0101 -(取反)
0b1111 1111 1111 0110 -(加1)
0b1111 1111 1111 0110 -(得出-10的二進制)
  1. 按位與(&)
    同真為真,其余為假:清零特定位、取出特定位;
// 按位與(&)
  0b0000 1111 0000 1111
& 0b0000 0000 1111 1111
  ---------------------
  0b0000 0000 0000 1111
  1. 按位或(|)
    同假為假,其余為真:特定位置1
// 按位或(|)
  0b0000 1111 0000 1111
| 0b0000 0000 1111 1111
  ---------------------
  0b0000 1111 1111 1111
  1. 按位異或(^)
    異值為真,同值為假:特定位取反、交換兩變量的值;
// 按位異或(^)
  0b0000 1111 0000 1111
^ 0b0000 0000 1111 1111
  ---------------------
  0b0000 1111 1111 0000
  1. 取反(~)
    按位取反
// 取反(~)
~ 0b0000 1111 0000 1111
  ---------------------
  0b1111 0000 1111 0000
  1. 左移(<<)
    按位左移,高位丟棄,低位補0;
// 左移(<<)兩位
  0b1111 0000 0000 1111 << 2
  ---------------------
  0b1100 0000 0011 1100
  1. 右移(>>)
    按位右移,高位正數(shù)補0,負數(shù)補1;
// 右移(>>)兩位
  0b1111 0000 0000 1111 >> 2
  ---------------------
  0b0011 1100 0000 0011

(3) 手動實現(xiàn)屬性的set方法和get方法

// TODO: -----------------  Person類  -----------------
//#define TallMask 0b00000001 // 1
//#define RichMask 0b00000010 // 2
//#define HandsomeMask 0b0000100 // 4
#define TallMask (1<<0)
#define RichMask (1<<1)
#define HandsomeMask (1<<2)

@interface Person : NSObject {
    char _tallRichHandsome;  // 0b0000 0000
}
- (void)setTall:(BOOL)tall;
- (void)setRich:(BOOL)rich;
- (void)setHandsome:(BOOL)handsome;
- (BOOL)isTall;
- (BOOL)isRich;
- (BOOL)isHandsome;
@end

@implementation Person
- (void)setTall:(BOOL)tall {
    if (tall) { // 按位或 - 特定位置1
        _tallRichHandsome |= TallMask;
    } else { // 掩碼先取反,后按位與 - 特定位置0
        _tallRichHandsome &= ~TallMask;
    }
}
- (void)setRich:(BOOL)rich {
    if (rich) {
        _tallRichHandsome |= RichMask;
    } else {
        _tallRichHandsome &= ~RichMask;
    }
}
- (void)setHandsome:(BOOL)handsome {
    if (handsome) {
        _tallRichHandsome |= HandsomeMask;
    } else {
        _tallRichHandsome &= ~HandsomeMask;
    }
}
- (BOOL)isTall {
    // 按位與 - 取出特定位
    // 兩次取反!,強制轉(zhuǎn)換成BOOL類型
    return !!(_tallRichHandsome & TallMask);
}
- (BOOL)isRich {
    return !!(_tallRichHandsome & RichMask);
}
- (BOOL)isHandsome {
    return !!(_tallRichHandsome & HandsomeMask);
}
@end

// TODO: -----------------  main  -----------------
int main(int argc, const char * argv[]) {
    @autoreleasepool {
        Person *person  = [[Person alloc] init];
        person.tall = YES;
        person.rich = NO;
        person.handsome = YES;
        NSLog(@"tall: %d, rich: %d, handsome: %d", person.isTall, person.isRich, person.isHandsome);
    }
    return 0;
}

// 打印結(jié)果
Demo[1234:567890] tall: 1, rich: 0, handsome: 1

上述代碼可以正常存值和取值,但是可拓展性和可讀性差。


(4) 位域

位域聲明:位域名 : 位域長度

使用位域需要注意以下3點:

  • 如果一個字節(jié)所??臻g不夠存放另一位域時,應(yīng)從下一單元起存放該位域;
    也可以有意使某位域從下一單元開始。
  • 位域的長度不能大于數(shù)據(jù)類型本身的長度;
    比如int類型就不能超過32位二進制位。
  • 位域可以無位域名,這時它只用來作填充或調(diào)整位置;
    無名的位域是不能使用的。
// TODO: -----------------  Person類  -----------------
@interface Person : NSObject {
    // 位域,tall、rich、handsome按序各占1個二進制位
    struct {
        char tall : 1;
        char rich : 1;
        char handsome : 1;
    } _tallRichHandsome;
}
- (void)setTall:(BOOL)tall;
- (void)setRich:(BOOL)rich;
- (void)setHandsome:(BOOL)handsome;
- (BOOL)isTall;
- (BOOL)isRich;
- (BOOL)isHandsome;
@end

@implementation Person
- (void)setTall:(BOOL)tall {
    _tallRichHandsome.tall = tall;
}
- (void)setRich:(BOOL)rich {
    _tallRichHandsome.rich = rich;
}
- (void)setHandsome:(BOOL)handsome {
    _tallRichHandsome.handsome = handsome;
}
- (BOOL)isTall {
    // _tallRichHandsome.tall == 0b1
    // 0b1111 1111 == -1
    return !!_tallRichHandsome.tall;
}
- (BOOL)isRich {
    return !!_tallRichHandsome.rich;
}
- (BOOL)isHandsome {
    return !!_tallRichHandsome.handsome;
}
@end

// 打印結(jié)果
Demo[1234:567890] tall: 1, rich: 0, handsome: 1

上述代碼使用結(jié)構(gòu)體的位域,不需要再使用掩碼,缺點是效率比使用位運算時低。


(5) 共用體

// TODO: -----------------  Person類  -----------------
#define TallMask (1<<0)
#define RichMask (1<<1)
#define HandsomeMask (1<<2)

@interface Person : NSObject {
    union { // 共用體
        char bits;
        //struct 增加代碼可讀性,可注釋掉
        struct {
            char tall : 1;
            char rich : 1;
            char handsome : 1;
        };
    }_tallRichHandsome;
}
- (void)setTall:(BOOL)tall;
- (void)setRich:(BOOL)rich;
- (void)setHandsome:(BOOL)handsome;
- (BOOL)isTall;
- (BOOL)isRich;
- (BOOL)isHandsome;
@end

@implementation Person
- (void)setTall:(BOOL)tall {
    if (tall) {
        _tallRichHandsome.bits |= TallMask;
    } else {
        _tallRichHandsome.bits &= ~TallMask;
    }
}
- (void)setRich:(BOOL)rich {
    if (rich) {
        _tallRichHandsome.bits |= RichMask;
    } else {
        _tallRichHandsome.bits &= ~RichMask;
    }
}
- (void)setHandsome:(BOOL)handsome {
    if (handsome) {
        _tallRichHandsome.bits |= HandsomeMask;
    } else {
        _tallRichHandsome.bits &= ~HandsomeMask;
    }
}
- (BOOL)isTall {
    // 兩次取反!,強制轉(zhuǎn)換成BOOL類型
    return !!(_tallRichHandsome.bits & TallMask);
}
- (BOOL)isRich {
    return !!(_tallRichHandsome.bits & RichMask);
}
- (BOOL)isHandsome {
    return !!(_tallRichHandsome.bits & HandsomeMask);
}
@end

// 打印結(jié)果
Demo[1234:567890] tall: 1, rich: 0, handsome: 1

上述代碼使用共用體對數(shù)據(jù)進行位運算取值和賦值,效率高同時占用內(nèi)存少,代碼可讀性高。


(6) isa詳解

經(jīng)過以上分析,我們可以清晰地了解到位運算、位域以及共用體的相關(guān)知識。
下面我們深入分析isa的結(jié)構(gòu):

isa結(jié)構(gòu)

由上圖可知:
isa_t共用體存儲了8個字節(jié)64位的值,所有信息都存儲在bits中,這些值在結(jié)構(gòu)體中展現(xiàn)出來,這些值通過對bits進行掩碼位運算取出。

名稱 作用
nonpointer 0代表普通的指針,存儲著Class,Meta-Class對象的內(nèi)存地址;1代表優(yōu)化過,使用位域存儲更多的信息
has_assoc 是否有設(shè)置過關(guān)聯(lián)對象,如果沒有,釋放時會更快
has_cxx_dtor 是否有C++析構(gòu)函數(shù),如果沒有,釋放時會更快
shiftcls 存儲著Class、Meta-Class對象的內(nèi)存地址信息
magic 用于在調(diào)試時分辨對象是否未完成初始化
weakly_referenced 是否有被弱引用指向過,如果沒有,釋放時會更快
deallocating 對象是否正在釋放
has_sidetable_rc 引用計數(shù)器是否過大無法存儲在isa中;如果為1,那么引用計數(shù)會存儲在一個叫SideTable的類的屬性中
extra_rc 里面存儲的值是引用計數(shù)器減1

重點介紹一下shiftcls

  • shiftcls存儲著Class、Meta-Class對象的內(nèi)存地址信息;
  • 通過bits & ISA_MASK取得shiftcls的值;
  • 而掩碼ISA_MASK值為0x0000000ffffffff8ULL,說明Class、Meta-Class對象的內(nèi)存地址值后三位一定為0。

接下來驗證一下:

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        Person *person  = [[Person alloc] init];
        person.tall = YES;
        person.rich = NO;
        person.handsome = YES;
        NSLog(@"tall: %d, rich: %d, handsome: %d", person.isTall, person.isRich, person.isHandsome);
        NSLog(@"class: %p, meta-class: %p", [Person class], object_getClass([Person class]));
    }
    return 0;
}
// 打印結(jié)果
Demo[1234:567890] tall: 1, rich: 0, handsome: 1
Demo[1234:567890] class: 0x100001260, meta-class: 0x100001238

由打印結(jié)果可知:
class對象的地址值為0x100001260,尾數(shù)是0;meta-class對象的地址值為0x100001238,尾數(shù)是8;在16進制下,內(nèi)存地址的后三位都為0;驗證結(jié)束。


總結(jié)可知:

  • __arm64__架構(gòu)開始,isa指針不只是存儲了class對象或meta-class對象的地址;
  • 而是使用共用體結(jié)構(gòu)存儲了更多信息:
    其中shiftcls存儲了class或meta-class的地址;
    shiftcls需要同ISA_MASK進行按位&運算才可以取出class對象或meta-class對象的地址。
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

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

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