Objective-C中的block使用方式二

本文通过具体的代码示例介绍了Objective-C中Block的基本使用方法,包括如何定义Block、如何使用Block捕获变量以及一些实用的Block实例。

#import <Foundation/Foundation.h>


//定义一种block类型

typedef int(^compatetor)(int arg1, int arg2);

//实例化一个block对象

compatetor comp = ^(int arg1, int arg2){

    int result = 0;

    if(arg1 > arg2) {

        result = arg1;

    } else {

        result = arg2;

    }

    return result;

};


//正常的定义及实现block方法

int(^minvalue)(int, int) = ^(int inputa, int inputb){

    return MIN(inputa, inputb);

};


int main(int argc, const char * argv[]) {

    @autoreleasepool {

//a 值不可以变

        int a = 20;

        int(^blka)(void) = ^(){

            return a;

        };

        blka();

        NSLog(@"The a value could not be changed %d", blka());

//b 值可以改变

        __block int b = 20;

        int(^blkb)(void) = ^(){

            b = 40;

            return b;

        };

        blkb();

        

        NSLog(@"The b value could be changed %d", blkb());

        

        NSLog(@"the max value is %d", comp(33, 203));

        

        NSLog(@"The min value is %d", minvalue(33,102));

        

    }

    return 0;

}

Result:

2018-03-17 15:30:28.139641+0800 TOCBlockc[26893:1809406] The a value could not be changed 20

2018-03-17 15:30:28.139919+0800 TOCBlockc[26893:1809406] The b value could be changed 40

2018-03-17 15:30:28.139942+0800 TOCBlockc[26893:1809406] the max value is 203

2018-03-17 15:30:28.139956+0800 TOCBlockc[26893:1809406] The min value is 33

Program ended with exit code: 0


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值