黑马程序员 OC中的block的基础理解

来源:互联网 发布:mac下制作dmg到u盘 编辑:程序博客网 时间:2024/05/17 22:15

block是什么

block是c语言的一种数据类型,可以作为函数的参数,作为函数的参数时用的多一点,而作为函数的返回值相对用的较少

block的定义及block的基本用法,有三种形式:

1.无参无返回值 void(^myblock)()=^(){一段代码};


返回值(^myblock)(参数)

void(^myblock)()=^(){

    NSLog(@"hahaha");

};

myblock();//调用


2.有参无返回值  void(^myblock)(int)=^(int a){一段代码};

void(^myblock)(int num)=^(int num){

    NSLog(@"%d",num);

};

myblock(5);

3.有参有返回值 int(^myblock)(int)=^(int a){一段代码};

int(^myblock)(int num)=^(int num){

    return num+1;

};

int a=myblock(5);

NSLog(@"%d",a);

为了简化代码,方便使用可以用typedef进行优化,类型如下

无参无返回值     typedefvoid(^myblock) ();

有参无返回值     typedefvoid(^myblock1)(int );

有参有返回值     typedefint(^myblock2)(int,int );

/*

 block访问外部变量:

 可以访问全局变量、外部定义的局部变量和内部定义的变量

 可以修改全局变量和内部定义的变量,不可以修改外部定义的局部变量(除非被__block修饰)

 */

#import <Foundation/Foundation.h>

typedef void(^myblock) ();

typedef void(^myblock1) (int );

typedef int(^myblock2)(int,int );

int num=1;                                 //全局变量,可以修改

int main(int argc,constchar * argv[]) {

    @autoreleasepool {

        __blockint num1=2;         //外部定义的局部变量,不可以直接修改(除非被__block修饰)

        myblock block=^(){

            NSLog(@"hah%d",num1);

        };

        block();


        myblock1 block1=^(int a){

            int num2=3;                     //内部定义的变量,可以修改

            NSLog(@"a=%d",a);

        };

        block1(5);


        myblock2 block2=^(int b,int c){

            return b>c?b:c;

        };

        int max=block2(19,23);

        NSLog(@"max=%d",max);

    }

    return0;

}

block的基本应用场景

/*

 block作为函数的参数

 */

#import <Foundation/Foundation.h>

typedefvoid(^myType) ();//用typedef写一个block类型

void test(myType block){//把一个block类型写入test函数的参数项

        NSLog(@"haha");

}

int main()

{

    @autoreleasepool {

        myType block1;//在main函数中定义一个block数据类型

        test(block1);//调用test函数,把block传进去

    }

    return0;

}

block作为函数的返回值

/*无参无返回值

 mytype test(){

 mytype b=^(){

 NSLog(@"haha");

 };

 return b;

 }

 mytype block;

 block=test();

 block();

 有参无返回值

 mytype test1(){

 void(^mytype)(int,int)=^(int x,int y){

 NSLog(@"%d",x+y);

 };

 return mytype;

 }

 mytype block1=test1();

 block1(3,2);

 有参有返回值

 mytype test(){

 int(^myblock)(int,int)=^(int a,int s){

 return a+s;

 };

 return myblock;

 }

 mytype sum=test();

 int sum1=sum(2,3);

 NSLog(@"%d",sum1);

 */


0 0
原创粉丝点击