zoukankan      html  css  js  c++  java
  • OC中block对于变量的捕获

    block中对于变量的捕获分为三种: 值传递、指针传递和直接访问

    值传递

    block捕获的局部变量,用auto修饰的,auto一般省略

    #import <Foundation/Foundation.h>
    
    int main(int argc, const char * argv[]) {
        @autoreleasepool {
            int age = 10;
            void (^block)(void) = ^{
                NSLog(@"%d",age);
            };
            block();
        }
        return 0;
    }

    转为C++代码如下:

    struct __main_block_impl_0 {
      struct __block_impl impl;
      struct __main_block_desc_0* Desc;
      int age;
      __main_block_impl_0(void *fp, struct __main_block_desc_0 *desc, int _age, int flags=0) : age(_age) {
        impl.isa = &_NSConcreteStackBlock;
        impl.Flags = flags;
        impl.FuncPtr = fp;
        Desc = desc;
      }
    };
    void (*block)(void) = ((void (*)())&__main_block_impl_0((void *)__main_block_func_0, &__main_block_desc_0_DATA, age));

    这种直接捕获的age的值,为值传递

    指针传递

    block捕获局部的静态变量

    #import <Foundation/Foundation.h>
    
    int main(int argc, const char * argv[]) {
        @autoreleasepool {
            static int age = 10;
            void (^block)(void) = ^{
                NSLog(@"%d",age);
            };
            block();
        }
        return 0;
    }

    转为C++代码:

    struct __main_block_impl_0 {
      struct __block_impl impl;
      struct __main_block_desc_0* Desc;
      int *age;
      __main_block_impl_0(void *fp, struct __main_block_desc_0 *desc, int *_age, int flags=0) : age(_age) {
        impl.isa = &_NSConcreteStackBlock;
        impl.Flags = flags;
        impl.FuncPtr = fp;
        Desc = desc;
      }
    };
    
     void (*block)(void) = ((void (*)())&__main_block_impl_0((void *)__main_block_func_0, &__main_block_desc_0_DATA, &age));

    直接获取

    block捕获全局变量

    #import <Foundation/Foundation.h>
    
    int age = 10;
    
    int main(int argc, const char * argv[]) {
        @autoreleasepool {
            void (^block)(void) = ^{
                NSLog(@"%d",age);
            };
            block();
        }
        return 0;
    }

    转C++代码如下:

    struct __main_block_impl_0 {
      struct __block_impl impl;
      struct __main_block_desc_0* Desc;
      __main_block_impl_0(void *fp, struct __main_block_desc_0 *desc, int flags=0) {
        impl.isa = &_NSConcreteStackBlock;
        impl.Flags = flags;
        impl.FuncPtr = fp;
        Desc = desc;
      }
    };
    
    void (*block)(void) = ((void (*)())&__main_block_impl_0((void *)__main_block_func_0, &__main_block_desc_0_DATA));
  • 相关阅读:
    jupyter中使用熟悉的vim
    解决安装manjaro中安装ccs10.2的库缺失问题
    Markdown中公式
    诗就应该边读边品的,不要
    为neovim田间python3支持
    bilibili视频保存目录
    新工科教育--之我所见
    父母的爱 和汽车的后背箱
    解决manjaro中jupyter无法修改目录和默认浏览器的问题:
    解决jupyter的能打开python文件无法新建的问题
  • 原文地址:https://www.cnblogs.com/muzichenyu/p/14083602.html
Copyright © 2011-2022 走看看