Shark Deng

Interactive Designer @Shanju Design in Shanghai

touched caffe / mxnet / python / wordpress / bootstrap / Arduino / Raspberry Pi / webgl / three.js / PIXI / 3dMax

Email

Github

__block. 含义

2019-11-13 00:28:38

是闭包可以使用闭包外定义的变量。

block.h

 

//
// 知识点:__block
// 划重点:__block就是让闭包可以使用在闭包外定义的变量。


#ifndef block_h
#define block_h

#import <Foundation/Foundation.h>

void block();
#endif /* block_h */

 

block.m

//
// 知识点:__block
// 划重点:__block就是让闭包可以使用在闭包外定义的变量。



#import "block.h"

int global_i = 1;
static int static_global_j = 2;

void block() {
    
    static int static_k = 3;
    __block int val = 4;  //让闭包可以修改这个值,去掉__block修饰就会报错
    

    void (^myBlock)(void) = ^{
        global_i ++;
        static_global_j ++;
        static_k ++;
        val++; 
        NSLog(@"Block中 global_i = %d,static_global_j = %d,static_k = %d,val = %d",global_i,static_global_j,static_k,val);
    };
    
    global_i ++;
    static_global_j ++;
    static_k ++;
    val ++;
    NSLog(@"Block外 global_i = %d,static_global_j = %d,static_k = %d,val = %d",global_i,static_global_j,static_k,val);
    
    myBlock();
    

}

 



——By SharkDeng
如果你喜欢我的文章,欢迎红包赞赏

Leave a Reply

Your email address will not be published. Required fields are marked *