IOS-Block

Block初探

blcok的分类

  • 不同关键字修饰的变量autostatic
    在OC中有个默认的关键字auto,在我们创建局部变量的时候,会默认在局部变量前加上auto关键字进行修饰。auto关键字的含义就是它所修饰的变量会自动释放,也表示着它所修饰的变量会存放到栈空间,系统会自动对其进行释放。
  • __NSGlobalBlock__全局block,block没有访问外部变量,访问全局的变量,访问静态变量的block都是全局blcok
    static int a = 10;
    static NSString *s1 = @"str1";
    void (^globalBlock1)(void) = ^{
        NSLog(@"-----global block");
    };
    void (^globalBlock2)(void) = ^{
        NSLog(@"-----global block:%d",a);
    };
    void (^globalBlock3)(void) = ^{
        NSLog(@"-----global block:%@",s1);
    };
// 打印结果如下
<__NSGlobalBlock__: 0x1043a7068>
<__NSGlobalBlock__: 0x1043a7088>
<__NSGlobalBlock__: 0x1043a70a8>
  • __NSStackBlock__栈block,block访问外部auto变量就是栈block
    auto int b = 11;
    auto NSString *s = @"str";
    NSLog(@"%@%@",^{
        NSLog(@"name is:%d",b);
    },^{
        NSLog(@"name is:%@",s);
    });
// 打印结果如下
<__NSStackBlock__: 0x7ffeeb858c40>
<__NSStackBlock__: 0x7ffeeb858c18>
  • __NSMallocBlock__堆block,栈block进行copy操作之后就变为堆block
    auto int b = 11;
    self.block = ^{
        NSLog(@"name is:%d",b);
    };
    NSLog(@"%@----%@",self.block,
          [^{
            NSLog(@"name is:%d",b);
            } copy]
          );
// 打印结果如下
<__NSMallocBlock__: 0x60000096af40>
----<__NSMallocBlock__: 0x60000096a4f0>

在ARC环境下,编译器会根据情况自动将栈上的block复制到堆上,比如以下情况
block作为函数返回值时
将block赋值给__strong指针时
block作为Cocoa API中方法名含有usingBlock的方法参数时
block作为GCD API的方法参数时

block的变量捕获(capture)

  • 我们创建一个带外部参数的block,查看对应的结构
int c = 15;
int main(int argc, const char * argv[]) {
    @autoreleasepool {
        auto int a = 10;
        static int b = 20;
        NSObject *obj = [[NSObject alloc] init];
        void(^testBlock)(void) = ^{
            NSLog(@"------- block---arg1:%d---arg2:%d---arg3:%d---arg4:%@",a,b,c,obj);
        };
    }
    return 0;
}
  • 查看有外部参数block的cpp文件,找到main函数,去掉一些强转代码,得到下面代码
int main(int argc, const char * argv[]) {
    /* @autoreleasepool */ { __AtAutoreleasePool __autoreleasepool; 

        auto int a = 10;
        static int b = 20;
        NSObject *obj = objc_msgSend)((id)(objc_msgSend)((id)objc_getClass("NSObject"), sel_registerName("alloc")), sel_registerName("init"));
        void(*testBlock)(void) = (&__main_block_impl_0(__main_block_func_0,                                                  &__main_block_desc_0_DATA,                                                                          a,                                                                         &b,                                                                        obj,                                                                570425344));
    }
    return 0;
}
  • 查看__main_block_impl_0的结构
struct __main_block_impl_0 {
  struct __block_impl impl;
  struct __main_block_desc_0* Desc;
  int a;
  int *b;
  NSObject *obj;
  __main_block_impl_0(void *fp, struct __main_block_desc_0 *desc, int _a, int *_b, NSObject *_obj, int flags=0) : a(_a), b(_b), obj(_obj) {
    impl.isa = &_NSConcreteStackBlock;
    impl.Flags = flags;
    impl.FuncPtr = fp;
    Desc = desc;
  }
};
---------------------------------------------------------------------------
struct __block_impl {
  void *isa;  //isa指针,可以看出Block其实就是一个OC对象
  int Flags;
  int Reserved;
  void *FuncPtr;  //函数内存地址
};
---------------------------------------------------------------------------
static struct __main_block_desc_0 {
  size_t reserved;
  size_t Block_size;
  void (*copy)(struct __main_block_impl_0*, struct __main_block_impl_0*);
  void (*dispose)(struct __main_block_impl_0*);
} __main_block_desc_0_DATA = { 0, sizeof(struct __main_block_impl_0), __main_block_copy_0, __main_block_dispose_0};
  • 为了保证block内部能够正常访问外部的变量,block有个变量捕获机制。
    • auto变量的捕获
      通过对上述代码的观察发现auto变量auto int a在struct __main_block_impl_0是以int a;的方式保存的。
    • static变量的捕获
      static变量static int b在struct __main_block_impl_0是以int *b;的方式保存的。
    • 对象类型的auto变量
      当block内部访问了对象类型的auto变量时
      如果block是在栈上,将不会对auto变量产生强引用
      如果block被拷贝到堆上
      会调用block内部的copy函数
      copy函数内部会调用_Block_object_assign函数
      _Block_object_assign函数会根据auto变量的修饰符(__strong、 __weak、__unsafe_unretained)做出相应的操作,形成强引用(retain)或者弱引用
      如果block从堆上移除
      会调用block内部的dispose函数
      dispose函数内部会调用_Block_object_dispose函数
      _Block_object_dispose函数会自动释放引用的auto变量(release)
  • block类型的总结
block的类型 block执行的操作
_NSGlobalBlock_ 没有访问auto类型的变量
_NSStackBlock_ 访问了auto类型的变量
_NSMallocBlock_ _NSStackBlock_类型的block执行了copy操作

__block修饰的变量

  • 当变量被__block修饰之后,在block结构体里面就不再是简单的值传递了,而是会将变量包装成一个__Block_byref_obj_0结构体,其结构如下
struct __Block_byref_obj_0 {
  void *__isa;
__Block_byref_obj_0 *__forwarding;
 int __flags;
 int __size;
 void (*__Block_byref_id_object_copy)(void*, void*);
 void (*__Block_byref_id_object_dispose)(void*);
 NSObject *obj;
};

// 对应的值
 __Block_byref_obj_0 obj = {(void*)0,
(__Block_byref_obj_0 *)&obj,
 33554432, sizeof(__Block_byref_obj_0), __Block_byref_id_object_copy_131, __Block_byref_id_object_dispose_131,
 ((NSObject *(*)(id, SEL))(void *)objc_msgSend)((id)objc_getClass("NSObject"), sel_registerName("new"))};

static void __Block_byref_id_object_copy_131(void *dst, void *src) {
 _Block_object_assign((char*)dst + 40, *(void * *) ((char*)src + 40), 131);
}
static void __Block_byref_id_object_dispose_131(void *src) {
 _Block_object_dispose(*(void * *) ((char*)src + 40), 131);
}

Block的循环引用

  • 在使用block的时候会遇到以下循环引用的问题,vc强引用着block,block强引用着vc,导致vc无法释放,不会执行dealloc。
typedef void(^block)(void);
@interface ViewController ()
@property (nonatomic, strong) NSString *name;
@property (nonatomic, strong) block block;
@end

@implementation ViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    self.name = @"xq";
    self.block = ^{
        NSLog(@"name is:%@",self.name);
    };
    self.block();
}
- (void)dealloc
{
    NSLog(@"%s",__func__);
}
@end
  • 知道产生了循环引用的原因,就可以通过一个弱引用的weakSelf指向self


    image.png
  • 所以我们只需要将上面的代码修改成如下,dealloc就会正常执行了
    __weak typeof(self) weakSelf = self;
    self.block = ^{
        NSLog(@"name is:%@",weakSelf.name);
    };
    // dealloc执行打印
    -[ViewController dealloc]
  • 但是我们将代码改成下面这样,又会出现问题了,由于vc已经释放了,所以再调用.name就为空
self.block = ^{
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            NSLog(@"name is:%@",weakSelf.name);
        });
    };
// 打印结果
-[ViewController dealloc]
 name is:(null)
  • 所以我们需要在block里面对weakSelf再进行一次强引用,这就是所谓weak-strong dance
self.block = ^{
        __strong typeof(weakSelf) strongSelf = weakSelf;//在arc中默认是strong的所以__strong是可以省略的
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            NSLog(@"name is:%@",strongSelf.name);
        });
    };
// 打印结果
name is:xq
-[ViewController dealloc]
  • 其他解决循环引用的方法
  • __block,这种方法的缺点是需要依赖block的调用,如果block不调用还是会有循环引用
    __block ViewController *vc = self;
    self.block = ^{
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            NSLog(@"name is:%@",vc.name);
            vc = nil;
        });
    };
    self.block();
  • 传值,通过将self作为参数传递给block
typedef void(^block)(ViewController *);
self.block = ^(ViewController *vc){
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            NSLog(@"name is:%@",vc.name);
        });
    };
 self.block(self);

Block的底层原理

clang研究blcok

  • 创建一个block,通过clang来观察下它的底层实现
    NSString *name = @"xq";
    void (^block)(void) = ^{
        NSLog(@"name is %@",name);
    };
    block();
  • clang后得到的代码如下
void (*block)(void) = ((void (*)())&__ViewController__viewDidLoad_block_impl_0((void *)__ViewController__viewDidLoad_block_func_0, &__ViewController__viewDidLoad_block_desc_0_DATA, name, 570425344));
((void (*)(__block_impl *))((__block_impl *)block)->FuncPtr)((__block_impl *)block);
//去掉一些强转
block = __ViewController__viewDidLoad_block_impl_0(__ViewController__viewDidLoad_block_func_0, __ViewController__viewDidLoad_block_desc_0_DATA,name, 570425344)
block-> FuncPtr(block)
  • __ViewController__viewDidLoad_block_impl_0的结构
  struct __ViewController__viewDidLoad_block_impl_0 {
  struct __block_impl impl;
  struct __ViewController__viewDidLoad_block_desc_0* Desc;
  NSString *name;
  // 结构体的构造函数
  __ViewController__viewDidLoad_block_impl_0(void *fp, struct __ViewController__viewDidLoad_block_desc_0 *desc, NSString *_name, int flags=0) : name(_name) {
    impl.isa = &_NSConcreteStackBlock;
    impl.Flags = flags;
    impl.FuncPtr = fp;
    Desc = desc;
  }
};
  • __block_impl的结构
struct __block_impl {
  void *isa;
  int Flags;
  int Reserved;
  void *FuncPtr;
};
  • __ViewController__viewDidLoad_block_desc_0的结构
static struct __ViewController__viewDidLoad_block_desc_0 {
  size_t reserved;
  size_t Block_size;
  void (*copy)(struct __ViewController__viewDidLoad_block_impl_0*, struct __ViewController__viewDidLoad_block_impl_0*);
  void (*dispose)(struct __ViewController__viewDidLoad_block_impl_0*);
} __ViewController__viewDidLoad_block_desc_0_DATA = { 0, sizeof(struct __ViewController__viewDidLoad_block_impl_0), __ViewController__viewDidLoad_block_copy_0, __ViewController__viewDidLoad_block_dispose_0};
// 因为我们捕获的变量是对象,所以需要对它的内存进行处理
static void __ViewController__viewDidLoad_block_copy_0(struct __ViewController__viewDidLoad_block_impl_0*dst, struct __ViewController__viewDidLoad_block_impl_0*src) {_Block_object_assign((void*)&dst->name, (void*)src->name, 3/*BLOCK_FIELD_IS_OBJECT*/);}

static void __ViewController__viewDidLoad_block_dispose_0(struct __ViewController__viewDidLoad_block_impl_0*src) {_Block_object_dispose((void*)src->name, 3/*BLOCK_FIELD_IS_OBJECT*/);}
  • __ViewController__viewDidLoad_block_func_0就是block要执行的任务
static void __ViewController__viewDidLoad_block_func_0(struct __ViewController__viewDidLoad_block_impl_0 *__cself) {
  NSString *name = __cself->name; // bound by copy

        NSLog((NSString *)&__NSConstantStringImpl__var_folders_13_ztl_wzln5357kbjwzx2pgrrw0000gp_T_ViewController_d580cd_mi_1,name);
    }
  • 总结 可以看到block底层是一个结构体,也是一个对象,通过构造函数将block的任务当做函数fp传递给结构体,再通过使用fp()调用,这也是外界调用block要用block()的原因,其本质就是函数的执行,所以block又叫匿名函数,对外界变量的捕获,当变量没有用block修饰的时候,会在block内部生成一个同名的变量并将外界变量的值传递进来,而当变量被__block修饰的时候,发现对象会被包装成__Block_byref_xxx_0的结构体,根据传入变量的类型会有不同的结构
struct __Block_byref_obj_0 {
  void *__isa;
__Block_byref_obj_0 *__forwarding;
 int __flags;
 int __size;
//对象类型会有这两个方法
 void (*__Block_byref_id_object_copy)(void*, void*);
 void (*__Block_byref_id_object_dispose)(void*);
 NSObject *obj;
};

汇编研究block的底层实现

  • 在blcok的开始处打下断点


    image.png
  • 进到汇编调试界面


    image.png
  • 加符号断点objc_retainBlock
    image.png
  • 进到符号断点


    image.png
  • 继续往下执行


    image.png
  • 最终会进入到libsystem_blocks.dylib_Block_copy
    image.png
  • 通过打印寄存器我们也可以发现执行完_Block_copy之后,block由栈block转换为堆block
  • 所以我们要研究block就要研究libsystem_blocks.dylib,获取它的源码

libsystem_blocks.dylib

  • 通过观察源码发现,block的底层其实是一个Block_layout的结构体其内部结构为
struct Block_layout {
    void *isa;
    volatile int32_t flags; // contains ref count
    int32_t reserved;
    BlockInvokeFunction invoke;
    struct Block_descriptor_1 *descriptor;
    // imported variables
};
  • isa:指向block的类型
  • flags:标识符,按bit位表示一些block的附加信息,类似于isa中的位域,其中flags的种类有以下几种,我们重点关注BLOCK_HAS_COPY_DISPOSE 和 BLOCK_HAS_SIGNATURE。 BLOCK_HAS_COPY_DISPOSE 决定是否有 Block_descriptor_2。BLOCK_HAS_SIGNATURE 决定是否有 Block_descriptor_3
// 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
};
  • reserved:保留信息
  • invoke:是一个函数指针,指向block中的代码
  • descriptor:block的附加信息,比如保留变量数、block的大小、copy或dispose的辅助函数指针,block的签名。有三类
    Block_descriptor_1是必选的
    Block_descriptor_2 和 Block_descriptor_3都是可选的
#define BLOCK_DESCRIPTOR_1 1
struct Block_descriptor_1 {
    uintptr_t reserved;
    uintptr_t size;
};

#define BLOCK_DESCRIPTOR_2 1
struct Block_descriptor_2 {
    // requires BLOCK_HAS_COPY_DISPOSE
    BlockCopyFunction copy;
    BlockDisposeFunction dispose;
};

#define BLOCK_DESCRIPTOR_3 1
struct Block_descriptor_3 {
    // requires BLOCK_HAS_SIGNATURE
    const char *signature;
    const char *layout;     // contents depend on BLOCK_HAS_EXTENDED_LAYOUT
};
  • 上面块描述器的构造函数如下,其中Block_descriptor_2和Block_descriptor_3都是通过Block_descriptor_1的地址内存平移得到的
#if 0
static struct Block_descriptor_1 * _Block_descriptor_1(struct Block_layout *aBlock)
{
    return aBlock->descriptor;
}
#endif

// Block 的描述 : copy 和 dispose 函数
static struct Block_descriptor_2 * _Block_descriptor_2(struct Block_layout *aBlock)
{
    if (! (aBlock->flags & BLOCK_HAS_COPY_DISPOSE)) return NULL;
    uint8_t *desc = (uint8_t *)aBlock->descriptor;
    desc += sizeof(struct Block_descriptor_1);
    return (struct Block_descriptor_2 *)desc;
}

//  Block 的描述 : 签名相关
static struct Block_descriptor_3 * _Block_descriptor_3(struct Block_layout *aBlock)
{
    if (! (aBlock->flags & BLOCK_HAS_SIGNATURE)) return NULL;
    uint8_t *desc = (uint8_t *)aBlock->descriptor;
    desc += sizeof(struct Block_descriptor_1);
    if (aBlock->flags & BLOCK_HAS_COPY_DISPOSE) {
        desc += sizeof(struct Block_descriptor_2);
    }
    return (struct Block_descriptor_3 *)desc;
}
  • _Block_copy的实现
void *_Block_copy(const void *arg) {
    struct Block_layout *aBlock;

    if (!arg) return NULL;
    
    // The following would be better done as a switch statement
    aBlock = (struct Block_layout *)arg;
    if (aBlock->flags & BLOCK_NEEDS_FREE) {
        // latches on high
        latching_incr_int(&aBlock->flags);
        return aBlock;
    }
    else if (aBlock->flags & BLOCK_IS_GLOBAL) {
        return aBlock;
    }
    else {
        // Its a stack block.  Make a copy.
        struct Block_layout *result =
            (struct Block_layout *)malloc(aBlock->descriptor->size);
        if (!result) return NULL;
        memmove(result, aBlock, aBlock->descriptor->size); // bitcopy first
#if __has_feature(ptrauth_calls)
        // Resign the invoke pointer as it uses address authentication.
        result->invoke = aBlock->invoke;
#endif
        // reset refcount
        result->flags &= ~(BLOCK_REFCOUNT_MASK|BLOCK_DEALLOCATING);    // XXX not needed
        result->flags |= BLOCK_NEEDS_FREE | 2;  // logical refcount 1
        _Block_call_copy_helper(result, aBlock);
        // Set isa last so memory analysis tools see a fully-initialized object.
        result->isa = _NSConcreteMallocBlock;
        return result;
    }
}
  • _Block_copy会对外界传入的blcok先做判断,如果需要释放或者是全局block直接返回block,需要释放的会对flag做一些处理,如果是栈block就会在堆中开辟一块空间,将传进来的blcok拷贝到开辟的空间中并把isa指向_NSConcreteMallocBlock_Block_call_copy_helper方法中对传递进来的参数做了一些处理
static void _Block_call_copy_helper(void *result, struct Block_layout *aBlock)
{
    struct Block_descriptor_2 *desc = _Block_descriptor_2(aBlock);
    if (!desc) return;

    (*desc->copy)(result, aBlock); // do fixup
}
  • 如果传入的参数不是对象类型的也就没有copy和dispose函数的就直接返回,否则就进入desc->copy方法,也就是外界传递过来的__Block_byref_id_object_copy_xx然后再调用_Block_object_assign对外界传递过来的参数处理
  • 外界传递过来的参数一般分为以下几种类型,我们重点研究BLOCK_FIELD_IS_OBJECTBLOCK_FIELD_IS_BYREF
//  Block 捕获的外界变量的种类
// 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_object_assign的实现
//  Block 捕获外界变量的操作
void _Block_object_assign(void *destArg, const void *object, const int flags) {
    const void **dest = (const void **)destArg;
    switch (os_assumes(flags & BLOCK_ALL_COPY_DISPOSE_FLAGS)) {
      case BLOCK_FIELD_IS_OBJECT:
        /*******
        id object = ...;
        [^{ object; } copy];
        ********/

        _Block_retain_object(object);
        *dest = object;
        break;

      case BLOCK_FIELD_IS_BLOCK:
        /*******
        void (^object)(void) = ...;
        [^{ object; } copy];
        ********/

        *dest = _Block_copy(object);
        break;
    
      case BLOCK_FIELD_IS_BYREF | BLOCK_FIELD_IS_WEAK:
      case BLOCK_FIELD_IS_BYREF:
        /*******
         // copy the onstack __block container to the heap
         // Note this __weak is old GC-weak/MRC-unretained.
         // ARC-style __weak is handled by the copy helper directly.
         __block ... x;
         __weak __block ... x;
         [^{ x; } copy];
         ********/

        *dest = _Block_byref_copy(object);
        break;
        
      case BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT:
      case BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK:
        /*******
         // copy the actual field held in the __block container
         // Note this is MRC unretained __block only. 
         // ARC retained __block is handled by the copy helper directly.
         __block id object;
         __block void (^object)(void);
         [^{ object; } copy];
         ********/

        *dest = object;
        break;

      case BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT | BLOCK_FIELD_IS_WEAK:
      case BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK  | BLOCK_FIELD_IS_WEAK:
        /*******
         // copy the actual field held in the __block container
         // Note this __weak is old GC-weak/MRC-unretained.
         // ARC-style __weak is handled by the copy helper directly.
         __weak __block id object;
         __weak __block void (^object)(void);
         [^{ object; } copy];
         ********/

        *dest = object;
        break;

      default:
        break;
    }
}
  • 如果是普通对象,则交给系统arc处理,并拷贝对象指针,即引用计数+1,所以外界变量不能释放
  • 如果是block类型的变量,则通过_Block_copy操作,将block从栈区拷贝到堆区
  • 如果是__block修饰的变量,调用_Block_byref_copy函数 进行内存拷贝以及常规处理
static struct Block_byref *_Block_byref_copy(const void *arg) {
    struct Block_byref *src = (struct Block_byref *)arg;

    if ((src->forwarding->flags & BLOCK_REFCOUNT_MASK) == 0) {
        // src points to stack
        struct Block_byref *copy = (struct Block_byref *)malloc(src->size);
        copy->isa = NULL;
        // byref value 4 is logical refcount of 2: one for caller, one for stack
        copy->flags = src->flags | BLOCK_BYREF_NEEDS_FREE | 4;
        copy->forwarding = copy; // patch heap copy to point to itself
        src->forwarding = copy;  // patch stack to point to heap copy
        copy->size = src->size;

        if (src->flags & BLOCK_BYREF_HAS_COPY_DISPOSE) {
            // Trust copy helper to copy everything of interest
            // If more than one field shows up in a byref block this is wrong XXX
            struct Block_byref_2 *src2 = (struct Block_byref_2 *)(src+1);
            struct Block_byref_2 *copy2 = (struct Block_byref_2 *)(copy+1);
            copy2->byref_keep = src2->byref_keep;
            copy2->byref_destroy = src2->byref_destroy;

            if (src->flags & BLOCK_BYREF_LAYOUT_EXTENDED) {
                struct Block_byref_3 *src3 = (struct Block_byref_3 *)(src2+1);
                struct Block_byref_3 *copy3 = (struct Block_byref_3*)(copy2+1);
                copy3->layout = src3->layout;
            }

            (*src2->byref_keep)(copy, src);
        }
        else {
            // Bitwise copy.
            // This copy includes Block_byref_3, if any.
            memmove(copy+1, src+1, src->size - sizeof(*src));
        }
    }
    // already copied to heap
    else if ((src->forwarding->flags & BLOCK_BYREF_NEEDS_FREE) == BLOCK_BYREF_NEEDS_FREE) {
        latching_incr_int(&src->forwarding->flags);
    }
    
    return src->forwarding;
}
  • 内部对Block_byref进行处理,如果已经在堆中对他递增并返回,如果没有将它拷贝到堆中并更新指针指向它

  • _Block_object_dispose就是对对象的销毁

void _Block_object_dispose(const void *object, const int flags) {
    switch (os_assumes(flags & BLOCK_ALL_COPY_DISPOSE_FLAGS)) {
      case BLOCK_FIELD_IS_BYREF | BLOCK_FIELD_IS_WEAK:
      case BLOCK_FIELD_IS_BYREF:
        // get rid of the __block data structure held in a Block
        _Block_byref_release(object);
        break;
      case BLOCK_FIELD_IS_BLOCK:
        _Block_release(object);
        break;
      case BLOCK_FIELD_IS_OBJECT:
        _Block_release_object(object);
        break;
      case BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT:
      case BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK:
      case BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT | BLOCK_FIELD_IS_WEAK:
      case BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK  | BLOCK_FIELD_IS_WEAK:
        break;
      default:
        break;
    }
}
  • _Block_byref_release的实现
static void _Block_byref_release(const void *arg) {
    struct Block_byref *byref = (struct Block_byref *)arg;

    // dereference the forwarding pointer since the compiler isn't doing this anymore (ever?)
    byref = byref->forwarding;
    
    if (byref->flags & BLOCK_BYREF_NEEDS_FREE) {
        int32_t refcount = byref->flags & BLOCK_REFCOUNT_MASK;
        os_assert(refcount);
        if (latching_decr_int_should_deallocate(&byref->flags)) {
            if (byref->flags & BLOCK_BYREF_HAS_COPY_DISPOSE) {
                struct Block_byref_2 *byref2 = (struct Block_byref_2 *)(byref+1);
                (*byref2->byref_destroy)(byref);
            }
            free(byref);
        }
    }
}

你可能感兴趣的:(IOS-Block)