iOS block的变量捕获(capture)

时间:2021-09-02 18:20:13

iOS block的变量捕获(capture)

变量捕获会在blcok结构体内部生成一个变量已来存储捕获到的指针或者值

#import "Person.h"

@implementation Person
/*
 oc每个函数后面都自带 (Person * self, SEL _cmd)
 -(void)test:(Person * self, SEL _cmd);
 而入参都是局部变量 所以下面代码会捕获 self 
 */
-(void)test{
    void (^bblock)(void)=^{
        NSLog(@"%@",self);
    };
    bblock();
}
/*
 struct __Person__test_block_impl_0 {
   struct __block_impl impl;
   struct __Person__test_block_desc_0* Desc;
   Person *self;
   __Person__test_block_impl_0(void *fp, struct __Person__test_block_desc_0 *desc, Person *_self, int flags=0) : self(_self) {
     impl.isa = &_NSConcreteStackBlock;
     impl.Flags = flags;
     impl.FuncPtr = fp;
     Desc = desc;
   }
 };
 
 static struct __Person__test_block_desc_0 {
   size_t reserved;
   size_t Block_size;
   void (*copy)(struct __Person__test_block_impl_0*, struct __Person__test_block_impl_0*);
   void (*dispose)(struct __Person__test_block_impl_0*);
 } __Person__test_block_desc_0_DATA = { 0, sizeof(struct __Person__test_block_impl_0), __Person__test_block_copy_0, __Person__test_block_dispose_0};

 static void _I_Person_test(Person * self, SEL _cmd) {
     void (*bblock)(void)=((void (*)())&__Person__test_block_impl_0((void *)__Person__test_block_func_0, &__Person__test_block_desc_0_DATA, self, 570425344));
     ((void (*)(__block_impl *))((__block_impl *)bblock)->FuncPtr)((__block_impl *)bblock);
 }
 
 */
@end