美文网首页
block的使用

block的使用

作者: Fight_Code | 来源:发表于2018-02-02 16:17 被阅读3次
    #import <Foundation/Foundation.h>
    @class EOCBlock;
    //枚举block
    typedef void (^TypedefBlock)(int param1, int param2);
    
    @interface EOCBlock : NSObject
    
    //声明block属性
    @property (nonatomic, copy)int (^oneParamBlock)(int param);
    @property (nonatomic, copy)void (^twoParamBlock)(int param1, int param2);
    @property (nonatomic, copy)int (^noParamBlock)(void);
    @property (nonatomic, assign)int result;
    
    -(void)doT;
    //block作为入参
    -(void)doTBlock:(void(^)(int param1, int param2))twoParamBlock;
    //block作为出参
    -(void(^)(int param1, int param2))doGetBlock;
    //block作为出参的应用
    -(EOCBlock *(^)(int param))doContinueBlock;
    @end
    
    #import "EOCBlock.h"
    
    @implementation EOCBlock
    
    -(void)doT{
        int v = self.oneParamBlock(5);
        NSLog(@"xxx:%d",v);
    }
    
    -(void)doTBlock:(void (^)(int, int))twoParamBlock
    {
        twoParamBlock(1,2);
        NSLog(@"doTBlock");
    }
    
    -(void (^)(int, int))doGetBlock
    {
        return ^(int p1,int p2){
            NSLog(@"doGetBlock : %d",p1);
        };
    }
    
    
    -(EOCBlock *(^)(int))doContinueBlock
    {
        return ^EOCBlock *(int p){
            _result *= p;
            return self;
        };
    }
    
    @end
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        
        __block int mult = 2;
        
        EOCBlock *e = [[EOCBlock alloc] init];
        e.oneParamBlock = ^int(int param) {
            //如果想要在block修改外部的变量,外部的变量需要用static、全局、__block
            mult = 3;
            return param * mult;
        };
        //必须先初始化block,再输出
        [e doT];
        
        NSLog(@"%@",e.oneParamBlock);
        
        //block作为入参
        [e doTBlock:^(int param1, int param2) {
            NSLog(@"param1:%d",param1);
        }];
        
        //block作为出参
        void (^block)(int,int) = [e doGetBlock];
        block(1,2);
        
        //block出参应用
        e.result = 1;
        e.doContinueBlock(1).doContinueBlock(2).doContinueBlock(3);
        NSLog(@"result:%d",e.result);
    }
    

    相关文章

      网友评论

          本文标题:block的使用

          本文链接:https://www.haomeiwen.com/subject/yrsezxtx.html