Objective-C语言——Block块

来源:互联网 发布:数据法则txt下载 编辑:程序博客网 时间:2024/06/06 23:52



#import "ViewController.h"


@interface ViewController ()


@end


int num = 100;


@implementation ViewController


- (void)viewDidLoad {

    [superviewDidLoad];

    // Do any additional setup after loading the view, typically from a nib.

    

    

    /**

     

     Block

     什么是 Block P201

     

     Block iOS4.0+ Mac OS X 10.6+ 引进的对 C语言的扩展,用来实现匿名函数的特征

        

        block C级别的匿名函数块 C语言的函数指针很像,在 iOS4.0之后就开始支持 block 

     

     iOS开发中什么情况使用 block

     1.代码的封装

     2.并发任务的执行

     3.回调

     

     block 块语法:

     

     返回值类型(^代码块名字)(参数列表) = ^(参数列表){代码块的行为主体};

     

     */

    

    //block 块的声明

    int (^Sum)(int n1,int n2);

    

    //block 块的实现

    Sum = ^(int n1,int n2){

        

        return n1 + n2;

    };

    

    //block 块的调用

    int result = Sum(1,3);

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

    

    

    //block 块的声明

    int (^Sum2)(int n1,int n2,int n3);

    

    //block 块的实现

    Sum2 =^(int n1,int n2,int n3){

    

        int max = n1;

        if (n1 < n2) {

            max = n2;

        } else {

            max = n3;

        }

        return max;

    };


    //block 块的调用

    int max = Sum2(1,3,2);

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

    

    

    //无返回值类型

    //声明

    void (^jack)(NSString *string);

    

    //实现

    jack =^(NSString *string){

    

        NSLog(@"%@",string);

    };

    

    jack(@"Rick");

    

    

    //在代码块中使用全局变量 局部变量

    //声明和实现全局变量

    void(^myBlockOne)() = ^() {

        

        num++;

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

        

    };

    

    //调用

    myBlockOne();

    

    

    __blockint numTwo = 100;

    void(^myBlockTwo)() = ^() {

        

        //        numTwo++;  //意味着局部变量可以使用,但不能改变它,那如何在中代码块中改变局部变量呢?子啊局部变量前面加上关键字:__block ,注意这里的 block关键字前面是两个下划线。

        

        numTwo++;

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

    };

    

    myBlockTwo();

}


- (void)didReceiveMemoryWarning {

    [superdidReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}


@end


0 0
原创粉丝点击