iOS中Block實現原理的全面分析

本人簡書地址iOS中Block實現原理的全面分析html

Block的底層基本結構

void blockTest()
{
    void (^block)(void) = ^{
        NSLog(@"Hello World!");
    };
    block();
}

int main(int argc, char * argv[]) {
    @autoreleasepool {
        blockTest();
    }
}
複製代碼

經過clang命令查看編譯器是如何實現Block的,在終端輸入clang -rewrite-objc main.m,而後會在當前目錄生成main.cpp的C++文件,代碼以下:c++

struct __blockTest_block_impl_0 {
  struct __block_impl impl;
  struct __blockTest_block_desc_0* Desc;
  __blockTest_block_impl_0(void *fp, struct __blockTest_block_desc_0 *desc, int flags=0) {
    impl.isa = &_NSConcreteStackBlock;
    impl.Flags = flags;
    impl.FuncPtr = fp;
    Desc = desc;
  }
};

static void __blockTest_block_func_0(struct __blockTest_block_impl_0 *__cself) {

        NSLog((NSString *)&__NSConstantStringImpl__var_folders_04_xwbq8q6n0p1dmhhd6y51_vbc0000gp_T_main_0048d2_mi_0);
    }
    

static struct __blockTest_block_desc_0 {
  size_t reserved;
  size_t Block_size;
} __blockTest_block_desc_0_DATA = { 0, sizeof(struct __blockTest_block_impl_0)};

void blockTest() {
    void (*block)(void) = ((void (*)())&__blockTest_block_impl_0((void *)__blockTest_block_func_0, &__blockTest_block_desc_0_DATA));
    ((void (*)(__block_impl *))((__block_impl *)block)->FuncPtr)((__block_impl *)block);
}

int main(int argc, char * argv[]) {
    /* @autoreleasepool */ { __AtAutoreleasePool __autoreleasepool; 
        blockTest();
    }
}

static struct IMAGE_INFO { unsigned version; unsigned flag; } _OBJC_IMAGE_INFO = { 0, 2 };

複製代碼

下面咱們一個一個來看macos

__blockTest_block_impl_0

struct __blockTest_block_impl_0 {
  struct __block_impl impl;
  struct __blockTest_block_desc_0* Desc;
  __blockTest_block_impl_0(void *fp, struct __blockTest_block_desc_0 *desc, int flags=0) {
    impl.isa = &_NSConcreteStackBlock;
    impl.Flags = flags;
    impl.FuncPtr = fp;
    Desc = desc;
  }
};
複製代碼

__blockTest_block_impl_0Block的C++實現,是一個結構體,從命名能夠看出表示blockTest中的第一個(0Block。一般包含兩個成員變量__block_impl impl__blockTest_block_desc_0* Desc和一個構造函數。bash

__block_impl

struct __block_impl {
  void *isa;
  int Flags;
  int Reserved;
  void *FuncPtr;
};

複製代碼

__block_impl也是一個結構體app

  • *isa:isa指針,指向一個類對象,有三種類型:_NSConcreteStackBlock、_NSConcreteGlobalBlock、_NSConcreteMallocBlock,本例中是_NSConcreteStackBlock類型。
  • Flags:block 的負載信息(引用計數和類型信息),按位存儲。
  • Reserved:保留變量。
  • *FuncPtr:一個指針,指向Block執行時調用的函數,也就是Block須要執行的代碼塊。在本例中是__blockTest_block_func_0函數。

__blockTest_block_desc_0

static struct __blockTest_block_desc_0 {
  size_t reserved;
  size_t Block_size;
} __blockTest_block_desc_0_DATA = { 0, sizeof(struct __blockTest_block_impl_0)};

複製代碼

__blockTest_block_desc_0是一個結構體,包含兩個成員變量:函數

  • reserved:Block版本升級所需的預留區空間,在這裏爲0。
  • Block_size:Block大小(sizeof(struct __blockTest_block_impl_0))

__blockTest_block_desc_0_DATA是一個__blockTest_block_desc_0的一個實例。post

__blockTest_block_func_0

__blockTest_block_func_0就是Block的執行時調用的函數,參數是一個__blockTest_block_impl_0類型的指針。學習

static void __blockTest_block_func_0(struct __blockTest_block_impl_0 *__cself) {

        NSLog((NSString *)&__NSConstantStringImpl__var_folders_04_xwbq8q6n0p1dmhhd6y51_vbc0000gp_T_main_0048d2_mi_0);
    }

複製代碼

blockTest

void blockTest() {
    void (*block)(void) = ((void (*)())&__blockTest_block_impl_0((void *)__blockTest_block_func_0, &__blockTest_block_desc_0_DATA));
    ((void (*)(__block_impl *))((__block_impl *)block)->FuncPtr)((__block_impl *)block);
}

複製代碼

第一部分,定義Blockui

void (*block)(void) = ((void (*)())&__blockTest_block_impl_0((void *)__blockTest_block_func_0, &__blockTest_block_desc_0_DATA));

複製代碼

咱們看到block變成了一個指針,指向一個經過__blockTest_block_impl_0構造函數實例化的結構體__blockTest_block_impl_0實例,__blockTest_block_impl_0在初始化的時候須要兩個個參數:atom

  • __blockTest_block_func_0Block塊的函數指針。
  • __blockTest_block_desc_0_DATA:做爲靜態全局變量初始化__main_block_desc_0的結構體實例指針。

第二部分,調用Block

((void (*)(__block_impl *))((__block_impl *)block)->FuncPtr)((__block_impl *)block);

複製代碼

((void (*)(__block_impl *))((__block_impl *)block)->FuncPtr)經過block->FuncPtr指針找到__blockTest_block_func_0函數而且轉成(void (*)(__block_impl *))類型。
((__block_impl *)block)而後將block做爲參數傳給這個函數調用。

Flags

__block_impl中咱們看到Flags,如今來詳細講一講。

在這裏Block_private.h能夠看到Flags的具體信息:

// Values for Block_layout->flags to describe block objects
enum {
    BLOCK_DEALLOCATING =      (0x0001),  // runtime
    BLOCK_REFCOUNT_MASK =     (0xfffe),  // runtime
    BLOCK_NEEDS_FREE =        (1 << 24), // runtime
    BLOCK_HAS_COPY_DISPOSE =  (1 << 25), // compiler
    BLOCK_HAS_CTOR =          (1 << 26), // compiler: helpers have C++ code
    BLOCK_IS_GC =             (1 << 27), // runtime
    BLOCK_IS_GLOBAL =         (1 << 28), // compiler
    BLOCK_USE_STRET =         (1 << 29), // compiler: undefined if !BLOCK_HAS_SIGNATURE
    BLOCK_HAS_SIGNATURE  =    (1 << 30), // compiler
    BLOCK_HAS_EXTENDED_LAYOUT=(1 << 31)  // compiler
};

複製代碼

引用淺談 block(1) - clang 改寫後的 block 結構的解釋:

也就是說,通常狀況下,一個 block 的 flags 成員默認設置爲 0。若是當 block 須要 Block_copy()Block_release 這類拷貝輔助函數,則會設置成 1 << 25 ,也就是 BLOCK_HAS_COPY_DISPOSE 類型。能夠搜索到大量講述 Block_copy 方法的博文,其中涉及到了 BLOCK_HAS_COPY_DISPOSE

總結一下枚舉類的用法,前 16 位即起到標記做用,又可記錄引用計數:

  • BLOCK_DEALLOCATING:釋放標記。通常經常使用 BLOCK_NEEDS_FREE 作 位與 操做,一同傳入 Flags ,告知該 block 可釋放。
  • BLOCK_REFCOUNT_MASK:通常參與判斷引用計數,是一個可選用參數。
  • BLOCK_NEEDS_FREE:經過設置該枚舉位,來告知該 block 可釋放。意在說明 block 是 heap block ,即咱們常說的 _NSConcreteMallocBlock 。
  • BLOCK_HAS_COPY_DISPOSE:是否擁有拷貝輔助函數(a copy helper function)。
  • BLOCK_HAS_CTOR:是否擁有 block 析構函數(dispose function)。
  • BLOCK_IS_GC:是否啓用 GC 機制(Garbage Collection)。
  • BLOCK_HAS_SIGNATURE:與 BLOCK_USE_STRET 相對,判斷是否當前 block 擁有一個簽名。用於 runtime 時動態調用。

block截獲變量

截獲auto變量值

Screen Shot 2019-05-03 at 3.47.08 PM.png

咱們看到直接在block修改變量會提示錯誤,爲何呢?

void blockTest()
{
    int num = 10;
    void (^block)(void) = ^{
        NSLog(@"%d",num);
    };
    num = 20;
    block();
}

int main(int argc, char * argv[]) {
    @autoreleasepool {
        blockTest();
    }
}

複製代碼

打印結果是10,clang改寫後的代碼以下:

struct __blockTest_block_impl_0 {
  struct __block_impl impl;
  struct __blockTest_block_desc_0* Desc;
  int num;
  __blockTest_block_impl_0(void *fp, struct __blockTest_block_desc_0 *desc, int _num, int flags=0) : num(_num) {
    impl.isa = &_NSConcreteStackBlock;
    impl.Flags = flags;
    impl.FuncPtr = fp;
    Desc = desc;
  }
};

static void __blockTest_block_func_0(struct __blockTest_block_impl_0 *__cself) {
  int num = __cself->num; // bound by copy

        NSLog((NSString *)&__NSConstantStringImpl__var_folders_04_xwbq8q6n0p1dmhhd6y51_vbc0000gp_T_main_3c2714_mi_0,num);
    }
    
    void blockTest() {
    int num = 10;
    void (*block)(void) = ((void (*)())&__blockTest_block_impl_0((void *)__blockTest_block_func_0, &__blockTest_block_desc_0_DATA, num));
    num = 20;
    ((void (*)(__block_impl *))((__block_impl *)block)->FuncPtr)((__block_impl *)block);
}

複製代碼

__blockTest_block_impl_0多了一個成員變量int num;,再看看構造函數__blockTest_block_impl_0(void *fp, struct __blockTest_block_desc_0 *desc, int _num, int flags=0),能夠看到第三個參數只是變量的值,這也就解釋了爲何打印的是10,由於**block截獲的是值**。

使用static修飾變量

void blockTest()
{
    static int num = 10;
    void (^block)(void) = ^{
        NSLog(@"%d",num);
        num = 30;
    };
    num = 20;
    block();
    NSLog(@"%d",num);
}

複製代碼

能夠在block內部修改變量了,同時打印結果是20,30。clang改寫後的代碼以下:

struct __blockTest_block_impl_0 {
  struct __block_impl impl;
  struct __blockTest_block_desc_0* Desc;
  int *num;
  __blockTest_block_impl_0(void *fp, struct __blockTest_block_desc_0 *desc, int *_num, int flags=0) : num(_num) {
    impl.isa = &_NSConcreteStackBlock;
    impl.Flags = flags;
    impl.FuncPtr = fp;
    Desc = desc;
  }
};

static void __blockTest_block_func_0(struct __blockTest_block_impl_0 *__cself) {
  int *num = __cself->num; // bound by copy

        NSLog((NSString *)&__NSConstantStringImpl__var_folders_04_xwbq8q6n0p1dmhhd6y51_vbc0000gp_T_main_5a95f6_mi_0,(*num));
        (*num) = 30;
    }
    
    void blockTest() {
    static int num = 10;
    void (*block)(void) = ((void (*)())&__blockTest_block_impl_0((void *)__blockTest_block_func_0, &__blockTest_block_desc_0_DATA, &num));
    num = 20;
    NSLog((NSString *)&__NSConstantStringImpl__var_folders_04_xwbq8q6n0p1dmhhd6y51_vbc0000gp_T_main_5a95f6_mi_1,num);
    ((void (*)(__block_impl *))((__block_impl *)block)->FuncPtr)((__block_impl *)block);
}

複製代碼

__blockTest_block_impl_0多了一個成員變量int *num;,和上面不一樣的是,此次**block截獲的是指針**,因此能夠在內部經過指針修改變量的值,同時在外部修改變量的值,block也能"感知到"。那麼爲何以前傳遞指針呢?由於變量是棧上,做用域是函數blockTest內,那麼有可能變量比block先銷燬,這時候block再經過指針去訪問變量就會有問題。而static修飾的變量不會被銷燬,也就不用擔憂。

全局變量

int num = 10;

void blockTest()
{
    void (^block)(void) = ^{
        NSLog(@"%d",num);
        num = 30;
    };
    num = 20;
    block();
    NSLog(@"%d",num);
}

複製代碼

打印結果是20,30。clang改寫後的代碼以下:

int num = 10;


struct __blockTest_block_impl_0 {
  struct __block_impl impl;
  struct __blockTest_block_desc_0* Desc;
  __blockTest_block_impl_0(void *fp, struct __blockTest_block_desc_0 *desc, int flags=0) {
    impl.isa = &_NSConcreteStackBlock;
    impl.Flags = flags;
    impl.FuncPtr = fp;
    Desc = desc;
  }
};

static void __blockTest_block_func_0(struct __blockTest_block_impl_0 *__cself) {

        NSLog((NSString *)&__NSConstantStringImpl__var_folders_04_xwbq8q6n0p1dmhhd6y51_vbc0000gp_T_main_1875c6_mi_0,num);
        num = 30;
    }

複製代碼

很是簡單,在初始化__blockTest_block_impl_0並無把num做爲參數,__blockTest_block_func_0中也是直接訪問全局變量。

總結:

變量類型 是否捕獲到block內部 訪問方式
局部auto變量 值傳遞
局部static變量 指針傳遞
全局變量 直接訪問

使用__block修飾變量

void blockTest()
{
    __block int num = 10;
    void (^block)(void) = ^{
        NSLog(@"%d",num);
        num = 30;
    };
    num = 20;
    block();
    NSLog(@"%d",num);
}

複製代碼

效果和使用static修飾變量同樣,clang改寫後的代碼以下:

struct __Block_byref_num_0 {
  void *__isa;
__Block_byref_num_0 *__forwarding;
 int __flags;
 int __size;
 int num;
};

struct __blockTest_block_impl_0 {
  struct __block_impl impl;
  struct __blockTest_block_desc_0* Desc;
  __Block_byref_num_0 *num; // by ref
  __blockTest_block_impl_0(void *fp, struct __blockTest_block_desc_0 *desc, __Block_byref_num_0 *_num, int flags=0) : num(_num->__forwarding) {
    impl.isa = &_NSConcreteStackBlock;
    impl.Flags = flags;
    impl.FuncPtr = fp;
    Desc = desc;
  }
};

static void __blockTest_block_func_0(struct __blockTest_block_impl_0 *__cself) {
  __Block_byref_num_0 *num = __cself->num; // bound by ref

        NSLog((NSString *)&__NSConstantStringImpl__var_folders_04_xwbq8q6n0p1dmhhd6y51_vbc0000gp_T_main_018b76_mi_0,(num->__forwarding->num));
        (num->__forwarding->num) = 30;
    }
    
static void __blockTest_block_copy_0(struct __blockTest_block_impl_0*dst, struct __blockTest_block_impl_0*src) {_Block_object_assign((void*)&dst->num, (void*)src->num, 8/*BLOCK_FIELD_IS_BYREF*/);}

static void __blockTest_block_dispose_0(struct __blockTest_block_impl_0*src) {_Block_object_dispose((void*)src->num, 8/*BLOCK_FIELD_IS_BYREF*/);}

static struct __blockTest_block_desc_0 {
  size_t reserved;
  size_t Block_size;
  void (*copy)(struct __blockTest_block_impl_0*, struct __blockTest_block_impl_0*);
  void (*dispose)(struct __blockTest_block_impl_0*);
} __blockTest_block_desc_0_DATA = { 0, sizeof(struct __blockTest_block_impl_0), __blockTest_block_copy_0, __blockTest_block_dispose_0};

void blockTest() {
    __attribute__((__blocks__(byref))) __Block_byref_num_0 num = {(void*)0,(__Block_byref_num_0 *)&num, 0, sizeof(__Block_byref_num_0), 10};
    void (*block)(void) = ((void (*)())&__blockTest_block_impl_0((void *)__blockTest_block_func_0, &__blockTest_block_desc_0_DATA, (__Block_byref_num_0 *)&num, 570425344));
    (num.__forwarding->num) = 20;
    ((void (*)(__block_impl *))((__block_impl *)block)->FuncPtr)((__block_impl *)block);
    NSLog((NSString *)&__NSConstantStringImpl__var_folders_04_xwbq8q6n0p1dmhhd6y51_vbc0000gp_T_main_018b76_mi_1,(num.__forwarding->num));
}

複製代碼

哇,難受啊兄dei,怎麼多出來這麼多東西,不要緊,慢慢分析。

__blockTest_block_impl_0多出來一個成員變量__Block_byref_num_0 *num;,咱們看到通過__block修飾的變量類型變成告終構體__Block_byref_num_0__blockTest_block_impl_0多出來一個成員變量__Block_byref_num_0 *num;block捕獲的是__Block_byref_num_0類型指針

__Block_byref_num_0
咱們看到__Block_byref_num_0是一個結構體,而且有一個isa,所以咱們能夠知道它其實就是一個對象。同時還有一個__Block_byref_a_0 *類型的__forwardingnumnum咱們能猜到就是用來保存變量的值,__forwarding就有一點複雜了,後面慢慢講。

__blockTest_block_copy_0和**__blockTest_block_dispose_0**

__blockTest_block_copy_0中調用的是_Block_object_assign__blockTest_block_dispose_0中調用的是_Block_object_dispose

函數 調用時機
__blockTest_block_copy_0 __block變量結構體實例從棧拷貝到堆時
__blockTest_block_dispose_0 __block變量結構體實例引用計數爲0時

關於_Block_object_assign_Block_object_dispose更詳細代碼能夠在runtime.c 中查看。

BLOCK_FIELD_IS_BYREF
咱們看到_Block_object_assign_Block_object_dispose中都有個參數值爲8,BLOCK_FIELD_IS_BYREF類型,什麼意思呢?在Block_private.h 中能夠查看到:

// Runtime support functions used by compiler when generating copy/dispose helpers

// Values for _Block_object_assign() and _Block_object_dispose() parameters
enum {
    // see function implementation for a more complete description of these fields and combinations
    BLOCK_FIELD_IS_OBJECT   =  3,  // id, NSObject, __attribute__((NSObject)), block, ...
    BLOCK_FIELD_IS_BLOCK    =  7,  // a block variable
    BLOCK_FIELD_IS_BYREF    =  8,  // the on stack structure holding the __block variable
    BLOCK_FIELD_IS_WEAK     = 16,  // declared __weak, only used in byref copy helpers
    BLOCK_BYREF_CALLER      = 128, // called from __block (byref) copy/dispose support routines.
};
複製代碼
  • BLOCK_FIELD_IS_OBJECT:OC對象類型
  • BLOCK_FIELD_IS_BLOCK:是一個block
  • BLOCK_FIELD_IS_BYREF:在棧上被__block修飾的變量
  • BLOCK_FIELD_IS_WEAK:被__weak修飾的變量,只在Block_byref管理內部對象內存時使用
  • BLOCK_BYREF_CALLER:處理Block_byref內部對象內存的時候會加的一個額外標記(告訴內部實現不要進行retain或者copy)

__blockTest_block_desc_0 咱們能夠看到它多了兩個回調函數指針*copy*dispose,這兩個指針會被賦值爲__main_block_copy_0__main_block_dispose_0

最後咱們看到訪問num是這樣的:

__Block_byref_num_0 *num = __cself->num; // bound by ref   

(num->__forwarding->num) = 30;
複製代碼

下面就講一講爲何要這樣。

Block的內存管理

在前面咱們講到__block_impl指向的_NSConcreteStackBlock類型的類對象,其實總共有三種類型:

類型 存儲區域
_NSConcreteStackBlock
_NSConcreteGlobalBlock 數據區
_NSConcreteMallocBlock

前面也講到copydispose,在ARC環境下,有哪些狀況編譯器會自動將棧上的把Block從棧上覆制到堆上呢?

Block從棧中複製到堆
調用Block的copy實例方法時
Block做爲函數返回值返回時
在帶有usingBlock的Cocoa方法或者GCD的API中傳遞Block時候
將block賦給帶有__strong修飾符的id類型或者Block類型時

Bock從棧中複製到堆,__block也跟着變化:

Screen Shot 2019-05-04 at 1.03.23 AM.png

  1. Block在棧上時,__block的存儲域是棧,__block變量被棧上的Block持有。
  2. Block被複制到堆上時,會經過調用Block內部的copy函數,copy函數內部會調用_Block_object_assign函數。此時__block變量的存儲域是堆,__block變量被堆上的Block持有。
  3. 當堆上的Block被釋放,會調用Block內部的disposedispose函數內部會調用_Block_object_dispose,堆上的__block被釋放。

Screen Shot 2019-05-04 at 1.09.18 AM.png

  1. 當多個棧上的Block使用棧上的__block變量,__block變量被棧上的多個Block持有。
  2. Block0被複制到堆上時,__block也會被複制到堆上,被堆上Block0持有。Block1仍然持有棧上的__block,原棧上__block變量的__forwarding指向拷貝到堆上以後的__block變量。
  3. Block1也被複制到堆上時,堆上的__block被堆上的Block0Block1只有,而且__block的引用計數+1。
  4. 當堆上的Block都被釋放,__block變量結構體實例引用計數爲0,調用_Block_object_dispose,堆上的__block被釋放。

下圖是描述__forwarding變化。這也就能解釋__forwarding存在的意義:

__forwarding 保證在棧上或者堆上都能正確訪問對應變量

Screen Shot 2019-05-04 at 2.52.00 PM.png

int main(int argc, char * argv[]) {

    int num = 10;

    NSLog(@"%@",[^{
        NSLog(@"%d",num);
    } class]);

    void (^block)(void) = ^{
        NSLog(@"%d",num);
    };

    NSLog(@"%@",[block class]);
}

複製代碼

打印結果:

2019-05-04 18:40:48.470228+0800 BlockTest[35824:16939613] __NSStackBlock__
2019-05-04 18:40:48.470912+0800 BlockTest[35824:16939613] __NSMallocBlock__

複製代碼

咱們能夠看到第一個Block沒有賦值給__strong指針,而第二個Block沒有賦值給__strong指針,因此第一個在棧上,而第二個在堆上。

Block截獲對象

int main(int argc, char * argv[]) {
    {
        Person *person = [[Person alloc] init];
        person.name = @"roy";

        NSLog(@"%@",[^{
            NSLog(@"%@",person.name);
        } class]);
        NSLog(@"%@",@"+++++++++++++");
    }
    NSLog(@"%@",@"------------");
}

複製代碼

打印結果:

@interface Person : NSObject
@property (nonatomic, strong) NSString *name;
@end

@implementation Person

- (void)dealloc {
    NSLog(@"-------dealloc-------");
}

@end

typedef void(^Block)(void);

int main(int argc, char * argv[]) {
    {
        Person *person = [[Person alloc] init];
        person.name = @"roy";

        NSLog(@"%@",[^{
            NSLog(@"%@",person.name);
        } class]);
        NSLog(@"%@",@"+++++++++++++");
    }
    NSLog(@"%@",@"------------");
}
複製代碼

咱們看到當Block內部訪問了對象類型的auto對象時,若是Block是在棧上,將不會對auto對象產生強引用。

auto Strong 對象

typedef void(^Block)(void);

int main(int argc, char * argv[]) {
    Block block;
    {
        Person *person = [[Person alloc] init];
        person.name = @"roy";

        block = ^{
            NSLog(@"%@",person.name);
        };
        person.name = @"david";
        NSLog(@"%@",@"+++++++++++++");
    }
    NSLog(@"%@",@"------------");
    block ();
}

複製代碼

打印結果是

2019-05-04 17:46:27.083280+0800 BlockTest[33745:16864251] +++++++++++++
2019-05-04 17:46:27.083934+0800 BlockTest[33745:16864251] ------------
2019-05-04 17:46:27.084018+0800 BlockTest[33745:16864251] david
2019-05-04 17:46:27.084158+0800 BlockTest[33745:16864251] -------dealloc-------

複製代碼

咱們看到是先打印的david再調用Person的析構方法dealloc,在終端輸入clang -rewrite-objc -fobjc-arc -fobjc-runtime=macosx-10.13 main.m -fobjc-arc,clang在ARC環境下改寫後的代碼以下:

struct __main_block_impl_0 {
  struct __block_impl impl;
  struct __main_block_desc_0* Desc;
  Person *__strong person;
  __main_block_impl_0(void *fp, struct __main_block_desc_0 *desc, Person *__strong _person, int flags=0) : person(_person) {
    impl.isa = &_NSConcreteStackBlock;
    impl.Flags = flags;
    impl.FuncPtr = fp;
    Desc = desc;
  }
};

複製代碼

咱們看到__main_block_impl_0中的Person *__strong person;成員變量。

Block截獲了auto對象,當Block被拷貝到堆上,Block強引用auto對象,這就能解釋了爲何超出了person的做用域,person沒有當即釋放,當Block釋放以後,會自動去掉對該對象的強引用,該對象就會被釋放了。

auto Weak 對象

typedef void(^Block)(void);

int main(int argc, char * argv[]) {
    Block block;
    {
        Person *person = [[Person alloc] init];
        person.name = @"roy";
        __weak Person *weakPerson = person;

        block = ^{
            NSLog(@"%@",weakPerson.name);
        };
        weakPerson.name = @"david";
        NSLog(@"%@",@"+++++++++++++");
    }
    NSLog(@"%@",@"------------");
    block ();
}

複製代碼

打印結果是

2019-05-04 17:49:38.858554+0800 BlockTest[33856:16869229] +++++++++++++
2019-05-04 17:49:38.859218+0800 BlockTest[33856:16869229] -------dealloc-------
2019-05-04 17:49:38.859321+0800 BlockTest[33856:16869229] ------------
2019-05-04 17:49:38.859403+0800 BlockTest[33856:16869229] (null)

複製代碼

直接在終端輸入clang -rewrite-objc main.m會報cannot create __weak reference because the current deployment target does not support weak ref錯誤。須要用clang -rewrite-objc -fobjc-arc -fobjc-runtime=macosx-10.13 main.m-fobjc-arc表明當前是ARC環境 -fobjc-runtime=macosx-10.13:表明當前運行時環境,缺一不可,clang以後的代碼:

struct __main_block_impl_0 {
  struct __block_impl impl;
  struct __main_block_desc_0* Desc;
  Person *__weak weakPerson;
  __main_block_impl_0(void *fp, struct __main_block_desc_0 *desc, Person *__weak _weakPerson, int flags=0) : weakPerson(_weakPerson) {
    impl.isa = &_NSConcreteStackBlock;
    impl.Flags = flags;
    impl.FuncPtr = fp;
    Desc = desc;
  }
};
複製代碼

咱們看到__main_block_impl_0中的Person *__weak weakPerson;成員變量。

總結:

  1. Block內部訪問了對象類型的auto對象時,若是Block是在棧上,將不會對auto對象產生強引用。
  2. 若是block被拷貝到堆上,會調用Block內部的copy函數,copy函數內部會調用_Block_object_assign函數,_Block_object_assign會根據auto對象的修飾符(__strong__weak__unsafe_unretained)作出相應的操做,當使用的是__strong時,將會對person對象的引用計數加1,當爲__weak時,引用計數不變。
  3. 若是Block從對上移除,會調用block內部的dispose函數,內部會調用_Block_object_dispose函數,這個函數會自動釋放引用的auto對象。

Block循環引用

@interface Person : NSObject

@property (nonatomic, strong) NSString *name;
@property (nonatomic, copy) void (^block)(void);

- (void)testReferenceSelf;

@end

@implementation Person

- (void)testReferenceSelf {
    self.block = ^ {
        NSLog(@"self.name = %s", self.name.UTF8String);
    };
    self.block();
}

- (void)dealloc {
    NSLog(@"-------dealloc-------");
}

@end


int main(int argc, char * argv[]) {
    Person *person = [[Person alloc] init];
    person.name = @"roy";
    [person testReferenceSelf];
}

複製代碼

打印結果是self.name = royPerson的析構方法dealloc並無執行,這是典型的循環引用,下面咱們研究研究爲啥會循環引用。clang改寫後的代碼以下:

struct __Person__testReferenceSelf_block_impl_0 {
  struct __block_impl impl;
  struct __Person__testReferenceSelf_block_desc_0* Desc;
  Person *const __strong self;
  __Person__testReferenceSelf_block_impl_0(void *fp, struct __Person__testReferenceSelf_block_desc_0 *desc, Person *const __strong _self, int flags=0) : self(_self) {
    impl.isa = &_NSConcreteStackBlock;
    impl.Flags = flags;
    impl.FuncPtr = fp;
    Desc = desc;
  }
};

static void _I_Person_testReferenceSelf(Person * self, SEL _cmd) {
    ((void (*)(id, SEL, void (*)()))(void *)objc_msgSend)((id)self, sel_registerName("setBlock:"), ((void (*)())&__Person__testReferenceSelf_block_impl_0((void *)__Person__testReferenceSelf_block_func_0, &__Person__testReferenceSelf_block_desc_0_DATA, self, 570425344)));
    ((void (*(*)(id, SEL))())(void *)objc_msgSend)((id)self, sel_registerName("block"))();
}

複製代碼

咱們看到原本Person中testReferenceSelf方法是沒有參數的,可是轉成C++以後多出來兩個參數:* self_cmd,再看看__Person__testReferenceSelf_block_impl_0中多出來一個成員變量Person *const __strong self;,所以咱們知道Person中block捕獲了selfblock強引用self,同時self也強引用block,所以造成循環引用。

Weak解除循環引用

@implementation Person

- (void)testReferenceSelf {
    __weak typeof(self) weakself = self;
    self.block = ^ {
        __strong typeof(self) strongself = weakself;
        NSLog(@"self.name = %s", strongself.name.UTF8String);
    };
    self.block();
}

- (void)dealloc {
    NSLog(@"-------dealloc-------");
}

@end

複製代碼

打印結果:

2019-05-04 19:27:48.274358+0800 BlockTest[37426:17007507] self.name = roy
2019-05-04 19:27:48.275016+0800 BlockTest[37426:17007507] -------dealloc-------

複製代碼

咱們看到Person對象被正常釋放了,說明不存在循環引用,爲何呢?clang改寫後的代碼以下:

struct __Person__testReferenceSelf_block_impl_0 {
  struct __block_impl impl;
  struct __Person__testReferenceSelf_block_desc_0* Desc;
  Person *const __weak weakself;
  __Person__testReferenceSelf_block_impl_0(void *fp, struct __Person__testReferenceSelf_block_desc_0 *desc, Person *const __weak _weakself, int flags=0) : weakself(_weakself) {
    impl.isa = &_NSConcreteStackBlock;
    impl.Flags = flags;
    impl.FuncPtr = fp;
    Desc = desc;
  }
};


static void _I_Person_testReferenceSelf(Person * self, SEL _cmd) {
    __attribute__((objc_ownership(weak))) typeof(self) weakself = self;
    ((void (*)(id, SEL, void (*)()))(void *)objc_msgSend)((id)self, sel_registerName("setBlock:"), ((void (*)())&__Person__testReferenceSelf_block_impl_0((void *)__Person__testReferenceSelf_block_func_0, &__Person__testReferenceSelf_block_desc_0_DATA, weakself, 570425344)));
    ((void (*(*)(id, SEL))())(void *)objc_msgSend)((id)self, sel_registerName("block"))();
}
複製代碼

能夠看到__Person__testReferenceSelf_block_impl_0結構體中weakself成員是一個__weak修飾的Person類型對象,也就是說__Person__testReferenceSelf_block_impl_0對Person的依賴是弱依賴。weak修飾變量是在runtime中進行處理的,在Person對象的Dealloc方法中會調用weak引用的處理方法,從weak_table中尋找弱引用的依賴對象,進行清除處理。

最後

好了,關於Block就寫到這裏了,花了五一的三天時間解決了一個基礎知識點,如釋重負,寫的真心累。

參考文章
淺談 block(1) - clang 改寫後的 block 結構
Objc Block實現分析
(四)Block之 __block修飾符及其存儲域
(三)Block之截獲變量和對象 關於Block再囉嗦幾句
__block變量存儲域
Block學習⑤--block對對象變量的捕獲
淺談Block實現原理及內存特性之三: copy過程分析
iOS底層原理總結 - 探尋block的本質(一)

相關文章
相關標籤/搜索