Block学习笔记二之几个简单的Block(贴代码)

#import "ViewController.h"


//声明 返回值为int 两个参数的block 别名为Addition 之后可以用Addition声明变量
typedef int(^Addition)(int a,int b);
//声明 返回值为int 两个参数的block 别名为Multiplication 之后可以用Multiplication声明变量
typedef int(^Multiplication)(int a,int b);

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    {
        //返回值是int类型 名字是count 参数是两个int类型 的block
        int (^count)(int,int) = ^(int a,int b){
            return a + b;
        };
        
        NSLog(@"8 + 7 = %d",count(8,7));
        
        //block作为变量赋值
        int (^count2)(int,int);
        count2 = count;
        NSLog(@"15 + 15 = %d",count2(15,15));
        
        //block作为函数参数
        [self myCount:^int(int a, int b) {
            return a + b;
        }];
        
        //block作为返回值
        count2 = [self returnMyBlock];
        NSLog(@"15 * 15 = %d",count2(15,15));
    }
    
    {
        //使用别名声明block变量
        
        Addition add1 = ^(int a,int b){
            return a + b;
        };
        
        Multiplication mult1 = ^(int a,int b){
            return a*b;
        };
        
        NSLog(@"666 + 666 = %d",add1(666,666));
        
        NSLog(@"666 * 1 = %d",mult1(666,1));
        
        //作为参数
        [self logAdd:add1];
        
        //作为返回值
        Multiplication mult2 = [self myMult];
        NSLog(@"100 * 199 = %d",mult2(100,100));
        
    }
    
    {
        //block截取自动变量
        int a = 10;
        int b = 99;
        
        //block截取了此刻a,b的值
        int(^add)() = ^{
            //a = 88;报错
            //b = 66;
            return a+b;
        };
        
        a = 0;
        b = 0;
        
        //上面修改a,b的值不影响block的执行结果
        NSLog(@"count : %d",add());
    }
    
    {
        //__block修饰符
        __block int a = 10;//a,b的值为10,99 顺序1
        __block int b = 99;
        
        //__block修饰符
        int(^add)() = ^{
            a = 88;//a,b的值为88,66  顺序3
            b = 66;
            return a+b;
        };
        
        a = 0;//a,b的值为0,0 顺序2
        b = 0;
        
        //log为 add : 154
        NSLog(@"count : %d",add());
    }
    
}

- (void)myCount:(int(^)(int,int)) countBlock{
    NSLog(@"30 + 30 = %d",countBlock(30,30));
}


- (int(^)(int,int))returnMyBlock{
    return ^(int a,int b){
        return a*b;
    };
}

- (void)logAdd:(Addition)add{
    NSLog(@"100 + 100 = %d",add(100,100));
}

- (Multiplication)myMult{
    Multiplication mult = ^(int a,int b){
        return a*b;
    };
    return mult;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容