函数指针过度倒Block思想

//声明函数 一

void test()

{

    NSLog(@"in test");

}

//声明函数 二

int addNum(int a,int b, int c){

    return a + b + c ;

}

 

//block 讲解

-(void)testBook

{

    

//    函数指针指向的是函数的地址        (^testBlock指向的是一个函数只有调用时才执行)

    //==========函数指针=========

//    1.申明

    void (*testP)() ;

//    2.赋值

    testP = &test;

//    3.调用

    (*testP)();

    

    //===========Block===========

//    1.申明一个Block

    void (^testBlock)();  //testBlock时变量 void (^)() 时类型

    

//    2.给Block负值

    

    testBlock = ^void () //block 就是没有函数名的函数 (赋值为void test()前面加^干掉变量)

    {

        NSLog(@"in testBlock 完整的负值方式");

    };

//    3.调用Block

       testBlock();

    

//    4.再次赋值

     testBlock = ^(){

        NSLog(@"任何返回值都可以掉");

    };

    //5.调用

    testBlock();

    

    //6.再次赋值

    testBlock = ^{

        NSLog(@"任何返回值都可以掉 参数为Void参数也可以去掉");

    };

    //7.调用

    testBlock();

    

    

    

    //=========带参数Block=====================

    

    //1.申明一个Block

    int  (^addNumBlock)(int a, int b ,int c );  // 类型是int  (^)(int a, int b ,int c ) 变量名addNumBlock

    

    //2.赋值  之间赋值 addNum

    

    addNumBlock  =  ^int (int a,int b, int c){

        return a + b + c ;

    };

    

   // 3.调用  只有调用后才执行

   int num =  addNumBlock(3,4,5);

    

    NSLog(@"%d",num);

    

    

    

   //=========Block做为参数============

    

    //调用 1.

   int nun2 = [self numAdd:^int(int a, int b, int c) {

       return a + b + c;

      } andA:1 andB:2 andC:3];

    

   //    调用2.

    int num3 = [self numAdd:addNumBlock andA:100 andB:200 andC:300];

 

//Block作为方法的参数

-(int)numAdd:(int(^)(int a, int b ,int c ))addNumBlock andA:(int)a andB:(int)b andC:(int)c

{

    return addNumBlock(a,b,c);

}

 

//============实际应用==第二个页面向第一个页面传值====

1.在第二个页面进行BLock声明

@property(nonatomic,copy)void(^changeColorBlock) (UIColor *color);

2.在第一个页面进行赋值

    __weak typeof (self) weakSelf = self;

    myView.changeColorBlock = ^(UIColor *color) {

                weakSelf.view.backgroundColor = color;

            };

 和下面等价------

//    [myView setChangeColorBlock:^(UIColor *color) {

//        weakSelf.view.backgroundColor = color;

//    }];

3.在第二个页面进行调用

    //调用Block

      if (self.changeColorBlock) {      

        self.changeColorBlock(color);

    }

 

posted @ 2015-08-25 19:04  BN笨的很想飞  阅读(197)  评论(0编辑  收藏  举报