傻瓜学编程之block_3

Posted 肖无情

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了傻瓜学编程之block_3相关的知识,希望对你有一定的参考价值。

block 捕获自动变量的瞬间值;

注释在代码中;请参考傻瓜学编程之block_3

 

import "People.h"
@interface People()
{
    int yourNameis;
   
    
}
@end


@implementation People
-(instancetype)init{
    if ( [super init]) {
        [self myBlcokTest];
    }
    return self;
    
    
    
}

- (void)myBlcokTest{
   int ddkknn = 555555;
    char bbb = \'3\';
    const char *fmt = &bbb;
    void (^blk)()=^{
        printf("%d",ddkknn);
        printf("%s",fmt);

    };
    blk();
    
  
}
// 变量直接添加 属性生成_xxxx;
struct People_IMPL {
    struct NSObject_IMPL NSObject_IVARS;
    int yourNameis;
    NSString *_thisIsPro;
};


/**
 1、结构体内部生成的成员变量与声明的成员变量的类型相同;
 2、block语法中没有使用的自动变量不会被追加,只有在block语法中使用的自动变量才会被追加;
 3、根据构造函数传递过来的参数对追加的成员变量进行初始化;
 */
struct __People__myBlcokTest_block_impl_0 {
    struct __block_impl impl;
    struct __People__myBlcokTest_block_desc_0* Desc;
    int ddkknn;
    const char *fmt;
    __People__myBlcokTest_block_impl_0(void *fp, struct __People__myBlcokTest_block_desc_0 *desc, int _ddkknn, const char *_fmt, int flags=0) : ddkknn(_ddkknn), fmt(_fmt) {
        impl.isa = &_NSConcreteStackBlock;
        impl.Flags = flags;
        impl.FuncPtr = fp;
        Desc = desc;
    }
    
//   相当于:
    __People__myBlcokTest_block_impl_0(void *fp, struct __People__myBlcokTest_block_desc_0 *desc, int _ddkknn, const char *_fmt, int flags=0) : ddkknn(_ddkknn), fmt(_fmt) {
        impl.isa = &_NSConcreteStackBlock;
        impl.Flags = flags;
        impl.FuncPtr = fp;
        Desc = desc;
        ddkknn = 5555;
        fmt = \'3\';
    }
};


//此时使用的是保存在__People__myBlcokTest_block_impl_0结构体实例的成员变量中那些自动变量的值 即(int ddkknn;
//const char *fmt;) 也就是截获自动变量 就是在执行block时,block所使用的自动变量保存在block 的结构体实例中;
static void __People__myBlcokTest_block_func_0(struct __People__myBlcokTest_block_impl_0 *__cself) {
    int ddkknn = __cself->ddkknn; // bound by copy
    const char *fmt = __cself->fmt; // bound by copy
    
    printf("%d",ddkknn);
    printf("%s",fmt);
    
}

static struct __People__myBlcokTest_block_desc_0 {
    size_t reserved;
    size_t Block_size;
} __People__myBlcokTest_block_desc_0_DATA = { 0, sizeof(struct __People__myBlcokTest_block_impl_0)};

static void _I_People_myBlcokTest(People * self, SEL _cmd) {
    int ddkknn = 555555;
    char bbb = \'3\';
    const char *fmt = &bbb;
    void (*blk)()=((void (*)())&__People__myBlcokTest_block_impl_0((void *)__People__myBlcokTest_block_func_0, &__People__myBlcokTest_block_desc_0_DATA, ddkknn, fmt));
    ((void (*)(__block_impl *))((__block_impl *)blk)->FuncPtr)((__block_impl *)blk);
    
    
}

 

以上是关于傻瓜学编程之block_3的主要内容,如果未能解决你的问题,请参考以下文章

傻瓜学编程之block_1

PAT乙级题库“傻瓜”题解之跟奥巴马一起编程

iOS学习之代码块(Block)

Vue之项目结构傻瓜式

面向面试编程代码片段之GC

block本质探寻七之内存管理