Block 简单使用

总是会忘记block的写法定义,记录几个常用的block.

 

@interface NextVC : UIViewController

@property(nonatomic,copy) void (^VoidBlack)(void);

@property(nonatomic,copy) void (^AgeBlock)(int age);

@property(nonatomic,copy) void (^PersonBlock)(NSString *person);

@end

 

- (IBAction)BackActions:(UIButton *)sender
{
    if (self.VoidBlack) {
        self.VoidBlack();
    }
    
    if (self.AgeBlock) {
        self.AgeBlock(23);
    }
    
    if (self.PersonBlock) {
        self.PersonBlock(@"PersonName");
    }
}

 

- (IBAction)JumpTwoVC:(UIButton *)sender
{
    NextVC *nextV = [[NextVC alloc]init];
    [self.navigationController pushViewController:nextV animated:YES];
    
    nextV.VoidBlack = ^{
      NSLog(@"OneBlock");
    };
    
    nextV.AgeBlock = ^(int age) {
        NSLog(@"Age = %i",age);
    };
}

 二、block 作为回参

/// 空block
-(void (^)(void))voidAction;

/// 传入字符串
- (void (^)(NSString *))strAction;

/// 传入字符串 返回字符串
- (NSString *(^)(NSString *))strBackStr;
-(void (^)(void))voidAction
{
    return ^(){
        NSLog(@"这是空方法");
    };
}

-(void (^)(NSString * _Nonnull))strAction
{
    return ^(NSString * _Nonnull name){
        NSLog(@"这是传入 %@",name);
    };
}

-(NSString * _Nonnull (^)(NSString * _Nonnull))strBackStr
{
    return ^(NSString * _Nonnull name) {
        NSString *msg = [NSString stringWithFormat:@"%@ liujf",name];
        NSLog(@"传入 %@ 返回 新 %@",name,msg);
        return msg;
    };
}
    AAA *adc = [[AAA alloc]init];
    adc.voidAction();
    adc.strAction(@"name");
    NSString *message = adc.strBackStr(@"ssss");
    NSLog(@"block = %@",message);

 

posted @ 2019-07-09 21:52  wq95230  阅读(142)  评论(0编辑  收藏  举报